public class Main2 {
public static void main(String[] args) {
int numOfStudent = 0;
boolean isInputValid = false;
// loop until user input a valid input
while (!isInputValid) {
try {
numOfStudent = Integer.parseInt(JOptionPane.showInputDialog(null, "how many students are there in the class"));
if (numOfStudent > 0) {
isInputValid = true;
} else {
throw new RuntimeException("invalid number");
}
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(null, "please input a valid number");
}
}
System.out.println("student number: " + numOfStudent);
// loop until all student info are recorded
int count = 0;
double total = 0.0;
while (count < numOfStudent) {
double age;
try {
age = Double.parseDouble(JOptionPane.showInputDialog(null, "please enter the age:"));
if (age >= 0) {
total += age;
count++;
} else {
throw new RuntimeException("invalid number");
}
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(null, "please input a valid age");
}
}
JOptionPane.showMessageDialog(null, "average age is: " + total / numOfStudent);
}
}
coursework
最新推荐文章于 2018-07-15 17:10:34 发布