简体   繁体   中英

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)

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).

If you want your loop to work on zero, and treat it as the exit mark too, switch from while to 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.

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( scan.hasNextInt() )

Then it will only loop as long as there are numbers. Inside the loop you can

input = scan.nextInt()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM