2011-02-15 60 views
7

如何阻止運行條件循環。例如,如果我寫的if聲明接受值從0到100怎麼辦,如果用戶輸入一個數小於0或超過100如何阻止在Java中運行循環

import java.util.Scanner; 
public class TestScores { 
    public static void main(String[]args) { 
      int numTests = 0; 
      double[] grade = new double[numTests]; 
      double totGrades = 0; 
      double average; 

      Scanner keyboard = new Scanner(System.in); 

      System.out.print("How many tests do you have? "); 

      numTests = keyboard.nextInt(); 
      grade = new double[(int) numTests]; 
      for (int index = 0; index < grade.length; index++) { 
        System.out.print("Enter grade for Test " + (index + 1) + ": "); 
        grade[index] = keyboard.nextDouble();        
        if (grade[index] < 0 || grade[index]> 100) { 
          try { 
           throw new InvalidTestScore(); 
          } 
       catch (InvalidTestScore e) { 
           e.printStackTrace(); 
          } 
        } 
      } 

      for (int index = 0; index < grade.length; index++) { 
        totGrades += grade[index]; 
      } 

      average = totGrades/grade.length; 
      System.out.print("The average is: " + average); 

    } 
} 

回答

18

您使用

break; 

關鍵字。這打破了一個循環。

1

這裏有一個提示停止程序,因爲這看起來像功課我說:你可以使用the break keyword,或使用條件:

if (grade[index] < 0 || grade[index]> 100) 
{ 
    // invalid grade... 
} 

爲一體的循環條件的一部分。

4

您可能需要使用break

for(int i=0; i<100; i++) 
{ 
    if(user entered invalid value) 
     break; // breaks out of the for loop 
}