How can I keep prompting the error message until a valid grade has been entered? Right now, I'm only prompted 4 times then the average is displayed.
Also, how would I calculate the average of only the three highest grades?
final int MAX_NUM_GRADES = 4;
double avg;
double sum = 0;
int count = 1;
double[] examGrade = new double[MAX_NUM_GRADES];
for (int i = 0; i < examGrade.length; i++) {
try {
examGrade[i] = Double.parseDouble(JOptionPane.showInputDialog("Enter Grade " + count + ":"));
if (examGrade[i] < 0 || examGrade[i] > 100) {
JOptionPane.showMessageDialog(null,"ERROR!.");
}
else {
count++;
sum = sum + examGrade[i];
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"ERROR!");
}
}
avg = sum/examGrade.length;
JOptionPane.showMessageDialog(null,"average exam grade is: "
+ String.format("%.1f",avg));
do-whileor awhile-doloop instead of aforloop; the termination condition would be eventually "when a valid grade is entered". Notice although you can use something similar with aforloop but the semantics might look "odd"