-4
年級平均程序在這裏;無法弄清楚如何處理輸入,如字符和字符串;嘗試trycatch和while/if(!input.hasNextInt/Double)。無法弄清楚。Java錯誤處理
import java.text.DecimalFormat;
import java.util.Scanner;
public class GradeAvgMinMax {
public static void main(String[] args) {
double largest = Double.MIN_VALUE;
double smallest = Double.MAX_VALUE;
double sum = 0;
Scanner input = new Scanner(System.in);
do {
System.out.println("How many grades would you like to enter?");
int num = input.nextInt();
for (int i = 1; i <= num; i++) {
System.out.println("Enter Grade: ");
double grade = input.nextDouble();
while (!input.hasNextInt() || !input.hasNextDouble()) {
System.out.println("Not a number!");
}
while (grade < 0) {
System.out.println("Grade cannot be negative, please retry");
System.out.println("Enter Grade: ");
grade = input.nextDouble();
}
while (grade > 100) {
System.out.println("Grade cannot be over 100, please retry");
System.out.println("Enter Grade: ");
grade = input.nextDouble();
}
if (grade > largest) {
largest = grade;
}
if (grade < smallest) {
smallest = grade;
}
sum = sum + grade;
}
double average = sum/num;
DecimalFormat df = new
DecimalFormat ("#.##");
System.out.println("AVG: " + df.format(average));
System.out.println("MAX: " + df.format(largest));
System.out.println("MIN: " + df.format(smallest));
System.out.println("Would you like to run this program again? (Y/N)");
} while ("Y".equalsIgnoreCase(input.next().trim()));
input.close();
}
}
想不通什麼? –