[英]Why does my program ignore zero when counting even numbers?
I'm having an issue when trying to count the number of even integers. 尝试计算偶数个整数时遇到问题。
This is the code I'm working with: 这是我正在使用的代码:
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;
}
}
I don't know how to set up the while loop: while (input! = 0)
我不知道如何设置while循环: while (input! = 0)
Given the test input 6, 4, -2, 0
it says that I have three even numbers, but the expected outcome is 4 (because 0
is even). 给定测试输入6, 4, -2, 0
它表示我有三个偶数,但预期结果为4(因为0
为偶数)。
If you want your loop to work on zero, and treat it as the exit mark too, switch from while
to do
/ while
: 如果您希望循环从零开始工作,并且也将其视为退出标记,请从while
切换为do
/ while
:
do {
input = scan.nextInt();
//calculates the total number of even integers
if (input%2 != 1)
{
numeven = numeven+1;
}
} while (input != 0);
This way your code will process zero along with regular inputs, and stop reading further input upon reaching the end of the loop. 这样,您的代码将与常规输入一起处理零,并在循环结束时停止读取其他输入。
You don't want the loop to break when the user enters a 0 or any other integer incase you want to put 0 multiple times. 您不希望在用户输入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);
Alternatively this does the same thing. 或者,这也做同样的事情。 Except it won't consume the last value. 除非它不会消耗最后的值。
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);
Just make the condition of your while loop to be 只要使您的while循环的条件为
while( scan.hasNextInt() )
Then it will only loop as long as there are numbers. 然后,只有存在数字时,它才会循环播放。 Inside the loop you can 在循环内您可以
input = scan.nextInt()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.