2012-10-09 26 views
1

我在寫一個簡單的程序來計算一組數字的平均值。您使用Scanner獲得數字,因此我使用while循環與.hasNext()作爲條件。然而,循環是無限的。Java - 如何突破與hasNext()條件?

是否有可能在沒有寫入輸入中的「停止」等特定字詞的情況下突破它?

public class main { 

    public static void main(String[] args){ 

     Scanner Input = new Scanner(System.in); 
     int count = 0; 
     int temp; 
     int sum = 0; 

     while(Input.hasNextInt()){ 

      count++;   

      temp = Input.nextInt(); 
      sum += temp; 
      System.out.println(temp); 
      System.out.println(count);   

     } // End of while 

     double average = sum/count; 
     System.out.println("The average is: " + average); 

    } // End of method main 

} 
+4

只需使用'打破;' – Baz

+0

你可能想使用一個哨兵值,使得用戶指定,當他們想退出。 – Sednus

+0

您希望用戶如何告訴程序沒有更多數據? – ddekany

回答

0

break;語句可以起訴...好...爆發的迭代。例如,通過迭代,我的意思是你也可以脫離for

你必須定義你想什麼時候打出來的迭代,然後做這樣的事情:

while(Input.hasNextInt(Input)){ 
    if(condition()) 
     break; 

    count++;   

    temp = Input.nextInt(); 
    sum += temp; 
    System.out.println(temp); 
    System.out.println(count);   

} 

否則,你可以定義如果迭代應該繼續走下去的輔助方法,像這樣的:

private boolean keepIterating(Scanner in) { 
    boolean someOtherCondition = //define your value here that must evaluate to false 
           //when you want to stop looping 
    return Input.hasNextInt() && someOtherCondition; 
} 

方法,你將不得不在你的while調用:

while(keepIterating()){ 

    count++;   

    temp = Input.nextInt(); 
    sum += temp; 
    System.out.println(temp); 
    System.out.println(count);   

} 
0

是,神奇的關鍵字是break;

1

你可以簡單地使用關鍵字break停止while循環:

while(Input.hasNextInt()){ 

    count++;   

    temp = Input.nextInt(); 
    sum += temp; 
    System.out.println(temp); 
    System.out.println(count); 
    break;   

} // End of while 
0

的問題是,Scanner總是期待System.in整數。你可以用一個基本的值例如跳出循環。 -1

if (temp == -1) { 
    break; 
} 
-2
public static void main(String[] args){ 

    Scanner Input = new Scanner(System.in); 

    System.out.println("Enter # to end "); 
    while(!Input.hasNextInt("#"))// return true if u input value = its argument 
    { 
     //ur code 
    }//end while