【发布时间】:2013-12-11 02:29:56
【问题描述】:
除此之外,我的程序中的所有内容都可以正常工作。我不明白问题是什么。如果用户输入超过 25 个等级,我需要程序吐出错误消息。这是我的代码
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);
}
我使用了我的整个代码,以防万一是 if 之外的东西导致了这种情况。每次我运行该程序时,它要求用户输入的窗口关闭了超过 25 次,并且没有弹出错误消息。我在这里做错了什么吗?
【问题讨论】:
-
if 在 do..while 循环之外
-
不,不是这样。这是我尝试的第一件事,但它仍然没有弹出。
标签: java arrays swing if-statement