2014-10-10 20 views
-1
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(); 
     } 
    } 
} 

控制檯輸出:我是新來的Java,我工作的一個項目,但我似乎無法得到for循環右

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: 
------------------------- 

任何建議將不勝感激。

+4

你的內循環實際上並不在你的外循環中。 – 2014-10-10 03:47:42

+0

如果我在s.next()之後使用},那麼它會在外部循環中,對嗎? – java 2014-10-10 03:58:33

+0

即使這樣,這個跟隨輸入考試的分數:輸出 「異常在線程‘主’java.util.InputMismatchException \t在java.util.Scanner.throwFor(未知來源) \t在java.util.Scanner.next (Unknown Source) \t at java.util.Scanner.nextDouble(Unknown Source) \t at test.main(test.java:31)「 – java 2014-10-10 03:59:45

回答

0

如果輸入一個無效的double,如「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 
    } 
} 
相關問題