[英]Why does my program ignore zero when counting even numbers?
嘗試計算偶數個整數時遇到問題。
這是我正在使用的代碼:
int input=0, numeven=0;
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
while (input != 0)
{
//calculates the total number of even integers
if (input%2 != 1)
{
numeven = numeven+1;
}
}
我不知道如何設置while循環: while (input! = 0)
給定測試輸入6, 4, -2, 0
它表示我有三個偶數,但預期結果為4(因為0
為偶數)。
如果您希望循環從零開始工作,並且也將其視為退出標記,請從while
切換為do
/ while
:
do {
input = scan.nextInt();
//calculates the total number of even integers
if (input%2 != 1)
{
numeven = numeven+1;
}
} while (input != 0);
這樣,您的代碼將與常規輸入一起處理零,並在循環結束時停止讀取其他輸入。
您不希望在用戶輸入0或任何其他整數的情況下中斷循環,以防您想多次輸入0。
int numeven=0;
Scanner scan = new Scanner(System.in);
while (true) {
String input = scan.next();
try {
int val = Integer.parseInt(input);
if (val % 2 == 0)
numeven++;
} catch (NumberFormatException e) {
//enter any input besides an integer and it will break the loop
break;
}
}
System.out.println("Total even numbers: " + numeven);
或者,這也做同樣的事情。 除非它不會消耗最后的值。
int numeven=0;
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
int val = scan.nextInt();
if (val % 2 == 0)
numeven++;
}
System.out.println("Total even numbers: " + numeven);
只要使您的while循環的條件為
while( scan.hasNextInt() )
然后,只有存在數字時,它才會循環播放。 在循環內您可以
input = scan.nextInt()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.