我在寫一個簡單的程序來計算一組數字的平均值。您使用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
}
只需使用'打破;' – Baz
你可能想使用一個哨兵值,使得用戶指定,當他們想退出。 – Sednus
您希望用戶如何告訴程序沒有更多數據? – ddekany