我是java的新手,我正在开发一个项目,但我似乎无法让for循环正确

时间:2014-10-10 03:43:29

标签: java for-loop nested-loops

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    System.out.println("Welcome to GradeCalculator!");
    System.out.println("\nPlease enter the number of students: ");
    int numberOfStudent = s.nextInt();
    System.out.println("Please enter the number of exams: ");
    int numberOfExams = s.nextInt();
    System.out.println();

    //outer loop for the number of students
    for (int i = 1; i <= numbeOfStudent; i++) {
        System.out.println("----------------------------------------");
        System.out.println("Enter student " + i + "'s " + "name: ");
        String name = s.nextLine();
        s.next();
    }
    System.out.println();

    //inner loop for the number of exams scores entered
    int sum = 0;
    for (int j = 1; j <= numberOfExam; j++) {
        System.out.print("Enter exam scores: ");
        double examScore = s.nextDouble();
        sum += examScore;

        if (examScore < 0) {
            System.out.println("Invalid exam scores, reenter: ");
            double examScoreReenter = s.nextDouble();
            sum += examScoreReenter;
        } else {
            System.out.println();
        }
    }
}

控制台输出:

Welcome to GradeCalculator!

Please enter the number of students: 
2
Please enter the number of exams: 
3

----------------------------------------
Enter student 1's name: 
john smith
----------------------------------------
Enter student 2's name: 
jane smith

Enter exam scores: "get exception"
------------------------------------------------------------------------

我几天来一直在努力奋斗,我无法理解。我想要的输出是:

-------------------------
Enter student 1's name : 
Enter exam score:
Invalid exam scores, reenter:
-------------------------

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果输入无效的双精度数,例如“thisisastringnotanumber”,则为InputMismatchException is thrown。你应该用try块包围你的nextDouble()调用以适应这个。

for (int j = 1; j <= numberOfExam; j++) {
    System.out.print("Enter exam scores: ");
    try{
        double examScore = s.nextDouble();

        if (examScore < 0) {
            System.out.println("Invalid exam scores, reenter: ");
            j--; //Retry this iteration
        } else {
            sum += examScore;
            System.out.println();
        }
    }catch(InputMismatchException e){
        System.out.println("Invalid exam scores, reenter: ");
        j--; //Retry this iteration
    }
}