0
我正在嘗試讀取未指定數量的整數,找到總和,積極,消極和平均的程序。我的問題是,要麼它只會運行,並允許鍵入一個整數,然後什麼都不做,或者用下面的代碼,它永遠不會讓你輸入數字,因此我無法越過。我有號碼= 0輸出正確。用戶輸入只出現一次或永遠不會停止在循環中
public class Compute {
// Count positive and negative numbers and compute the average of numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
positive = 0;
negative = 0;
total = 0;
System.out.println("Enter an integer, the input ends if it is 0: ");
int numbers = input.nextInt();
do {
if (numbers > 0) {
positive++;//add 1 to positive count
} else if (numbers < 0) {
negative++;//add 1 to negative count
}//end else if
sum += numbers; //add integer input to sum
numbers = input.nextInt();
total++;
} while (numbers != 0);
if (numbers == 0) {
System.out.println("No numbers are entered except " + numbers);
}//end if
}
}
請工作更好地對您的代碼進行格式化。如果人們可以輕鬆閱讀你的代碼,你會得到更好的答案。 –
輸入0退出循環。 –
另外,請考慮在每次調用input.nextInt()之前向用戶輸入提示。否則,您如何知道是時候輸入新的輸入了?例如:'System.out.print(「請輸入下一個數字:」);'後面跟'numbers = input.nextIne();' –