問題描述
當(dāng)輸入零并立即開始求和時,我需要停止詢問整數(shù)輸入.當(dāng)我輸入零時,我的程序不會停止.我需要它停止并開始總結(jié)它收集的所有輸入.
I need to stop asking for integer inputs when zero is typed as an input and start summation immediately. My program doesn't stop when I type zero. I need it to stop and start summing up all the inputs it has gathered.
這是我所擁有的:
public class Inttosum {
public static void main(String[] args) {
System.out.println("Enter an integer");
Scanner kb = new Scanner(System.in);
int askool = kb.nextInt();
int sum = 0;
int score = 0;
while(askool != 0){
score = kb.nextInt();
sum += score;
}
}
}
///////////////最終代碼有效..謝謝!公共類 Inttosum {
/////////////////The final code which worked..Thank you! public class Inttosum {
public static void main(String[] args) {
System.out.println("Enter an integer");
Scanner kb = new Scanner(System.in);
int sum = 0;
int score = 0;
do {
score = kb.nextInt();
sum += score;
}while(score != 0);
System.out.print(sum);
}
}
推薦答案
do-while
您正在使用稱為 askool
的東西作為循環(huán)條件,但在循環(huán)中更新變量 score
.您可以使用 do-while
循環(huán).改變
do-while
You are using something called askool
as a loop condition, but updating the variable score
in your loop. You could use a do-while
loop. Change
while(askool != 0){
score = kb.nextInt();
sum += score;
}
類似
do {
score = kb.nextInt();
sum += score;
}while(score != 0);
使用 break
我還建議調(diào)用 Scanner.hasNextInt()
在調(diào)用 nextInt
之前.而且,由于你不使用 score
(只是 sum
)你可以這樣寫,
Using break
I also suggest calling Scanner.hasNextInt()
before calling nextInt
. And, since you don't use the score
(just the sum
) you could write it like,
int sum = 0;
while (kb.hasNextInt()) {
int score = kb.nextInt();
if (score == 0) {
break;
}
sum += score;
}
System.out.print(sum);
如果用戶輸入文本,它也會停止(并且仍然 sum
所有 int
s).
Which will also stop (and still sum
all int
s) if the user enters text.
這篇關(guān)于讀取輸入,直到輸入特定數(shù)字的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!