2016-06-07 112 views
-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(); 

    } 

} 
+0

想不通什麼? –

回答

1

你正在做這整個錯誤。

System.out.println("Enter Grade: "); 
double grade = input.nextDouble(); 
while (!input.hasNextInt() || !input.hasNextDouble()) { 
    System.out.println("Not a number!"); 
} 

hasNextDouble()的javadoc說:

返回true,如果在此掃描器輸入信息的下一個標記可以解釋爲使用nextDouble()方法的雙重價值。掃描儀不會超過任何輸入。

如果hasNextDouble()返回false,則表示while循環將永久運行,因爲沒有任何更改。

您必須致電hasNextDouble()之前致電nextDouble()。這種方式nextDouble()永遠不會失敗,你不必捕捉異常。

但是,當hasNextDouble()返回false時,您仍然必須扔掉不良輸入。通過撥打nextLine()可以輕鬆完成。

因此,該代碼應該是這樣的:

double grade; 
for (;;) { // loop forever, i.e. until break 
    System.out.print("Enter Grade: "); 
    if (! input.hasNextDouble()) { 
     System.out.println("Not a number!"); 
     input.nextLine(); // discard bad input 
     continue; // loop back to try again 
    } 
    grade = input.nextDouble(); 
    input.nextLine(); // we only asked for one number, so discard any extra input following the number 
    if (grade < 0 || grade > 4.0) { 
     System.out.println("Number must be between 0 and 4"); 
     continue; // loop back to try again 
    } 
    break; // got good value, so exit loop 
}