JakeSteirer21
JakeSteirer21

Reputation: 23

Why is my while loop not stopping after I want it to?

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int number = 1;
        int[] arrayNumber = new int[10];
        do {
            System.out.println("Please enter numbers (0 to stop) : ");
            for (int i = 0; i < arrayNumber.length; i++) {
                arrayNumber[i] = scanner.nextInt();
                if (arrayNumber[i] == 0) {
                    number = 0;
                }
            }

        } while (number != 0);

I am trying to have the user enter numbers (up to 10) and is stopped once the user enters 0. But, when 0 is entered it does not stop.

Upvotes: 2

Views: 42

Answers (3)

Dmitriy Mishenyov
Dmitriy Mishenyov

Reputation: 329

The point is that your code would work properly only if you enter 0 at the last iteration at for loop. You can explicitly break your loop to let the while loop process your zero value and stop the loop.

    do {
        System.out.println("Please enter numbers (0 to stop) : ");
        for (int i = 0; i < arrayNumber.length; i++) {
            arrayNumber[i] = scanner.nextInt();
            if (arrayNumber[i] == 0) {
                number = 0;
                break;
            }
        }

    } while (number != 0);

Upvotes: 0

Abdul
Abdul

Reputation: 73

It is simply because you have an inner for loop, you're setting the number to 0 but the for loop still hasn't finished completing. Here would be the fix

This will finish executing after the user enters 10 numbers or enters 0, whichever comes first

Scanner scanner = new Scanner(System.in);

int[] arrayNumber = new int[10];
int maxNums = 0;

while (maxNums < 10) {
    arrayNumber[maxNums] = scanner.nextInt();
    if (arrayNumber[maxNums] == 0) break;
    maxNums++;
}

This is much shorter and neater, more readable

Upvotes: 1

maazakn
maazakn

Reputation: 404

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int number = 1;
        int[] arrayNumber = new int[10];
        do {
            System.out.println("Please enter numbers (0 to stop) : ");
            for (int i = 0; i < arrayNumber.length; i++) {
                arrayNumber[i] = scanner.nextInt();
                if (arrayNumber[i] == 0) {
                    number = 0;
                    break;
                }
            }  while (number != 0);

Upvotes: 0

Related Questions