简体   繁体   中英

Java do while loop not looping

I'm having a bit of trouble with this do while loop. The system will print out the line and stop. What am I doing wrong? Thank you for your time!

Scanner keyboard = new Scanner(System.in);

    String answer;
    int inputNum = 1;
    int countOdd = 0;
    int countEven = 0;

    do{
        do{
            System.out.println("Please enter an interger. When you are finished, enter 0.");
            inputNum = keyboard.nextInt();

                while (inputNum % 2 == 0)
                    countOdd++;
                while (inputNum % 2 != 0)
                    countEven++;
        }while(inputNum != 0);


        System.out.println("Thank you. The amount of odd intergers you entered is " 
        + countOdd + ". The amount of even intergers you entered is " + countEven);


        System.out.println("Thank you. The amount of odd intergers you entered is " 
        + countOdd + ". The amount of even intergers you entered is " + countEven);

        System.out.println("Would you like to run this program again? (Y) (N)");
        answer = keyboard.nextLine();

    }while (answer.equals("Y"));

    System.out.println("Thank you!");
}

}

The following loops cannot be finished, since inputNum is not changed inside:

          while (inputNum % 2 == 0)
                countOdd++;
          while (inputNum % 2 != 0)
                countEven++;

You need if statements here instead of while .

You need to change while with if . The logic inputNum%2==0 checks for even not odd.But if you did it intentionally opposite ,its fine. I changed it as it should be.

        Scanner keyboard = new Scanner(System.in);

    String answer;
    int inputNum = 1;
    int countOdd = 0;
    int countEven = 0;


        do{
            System.out.println("Please enter an interger. When you are finished, enter 0.");
            inputNum = keyboard.nextInt();

             if (inputNum % 2 == 0)
                 countEven++;
               if (inputNum % 2 != 0)
                   countOdd++;
        }while(inputNum != 0);


        System.out.println("Thank you. The amount of odd intergers you entered is " 
        + countOdd + ". The amount of even intergers you entered is " + countEven);

The problem is with the following lines of code

while (inputNum % 2 == 0)
                countOdd++;
while (inputNum % 2 != 0)
                countEven++;

You don't use while statements for if conditions. Instead use this

 if (inputNum % 2 == 0)
                    countOdd++;
 if (inputNum % 2 != 0)
                    countEven++;

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