我的計劃中的一切工作除此之外的工作。我看不出有什麼問題。如果用戶輸入超過25個等級,我需要該程序吐出一條錯誤消息。這裏是我的代碼我的if塊有什麼問題?
package my.meancalculator;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import java.text.DecimalFormat;
public class MeanCalcUI extends javax.swing.JFrame {
private final DecimalFormat formatter = new DecimalFormat("#0.0");
private double gradeAverage;
private double standardDeviation;
JFrame frame = new JFrame();
private double[] gradeArray = new double[25];
private int numberOfGradesInput = 0;
public MeanCalcUI() {
initComponents();
setLocationRelativeTo(null);
}
public double getAverage(double[] gradeArray, int numberOfGradesInput) {
double sum = 0;
for (int i = 0; i < numberOfGradesInput; i++) {
sum = sum + gradeArray[i];
}
return (sum/numberOfGradesInput);
}
public double getStdDev(double[] gradeArray, int numberOfGradesInput, double average) {
double sum = 0;
for (int i = 0; i < numberOfGradesInput; i++) {
sum = sum + Math.pow((gradeArray[i] - average), 2);
}
return Math.sqrt(sum/numberOfGradesInput);
}
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void btnEnterGradesActionPerformed(java.awt.event.ActionEvent evt) {
if (numberOfGradesInput > 25) {
// We've already finished entering the max # of grades
JOptionPane.showMessageDialog(frame,
"You can only input 25 grades!",
"Too much data!",
JOptionPane.ERROR_MESSAGE);
return;
}
do {
String gradeInput = JOptionPane.showInputDialog(frame,
"Enter Grade",
"Enter Grade",
JOptionPane.PLAIN_MESSAGE);
// When we receive empty/null input, we're done entering grades
if (gradeInput == null || gradeInput.length() == 0) {
break;
}
double gradeValue = 0; // Set to avoid 'may be unset' compiler error
try {
gradeValue = Double.parseDouble(gradeInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Your input must be numeric!",
"Bad Data!",
JOptionPane.ERROR_MESSAGE);
continue; // start over again
}
// Put the grade into the array and update the number of grades entered
gradeArray[numberOfGradesInput] = gradeValue;
numberOfGradesInput++;
// Add to the grade total
txtNumGrades.setText(formatter.format(numberOfGradesInput));
//use the getAverage method to get the average of the grades
gradeAverage = getAverage(gradeArray, numberOfGradesInput);
txtMean.setText(formatter.format(gradeAverage));
//use the getStdDev method to get the standard deviation
standardDeviation = getStdDev(gradeArray, numberOfGradesInput, gradeAverage);
txtStdDeviation.setText(formatter.format(standardDeviation));
} while (numberOfGradesInput < 25);
}
我用我的整個代碼,以防萬一它是如果這是造成這種情況。每次運行程序時,我都會輸入一個超過25倍的窗口號,並要求用戶輸入關閉,並且不會彈出錯誤消息。有什麼我在這裏做錯了嗎?
的,如果是do..while循環 – Taylor
之外不,不是這樣。這是第一個我嘗試過的東西仍然沒有彈出 – Akira