Kyle Butler
Kyle Butler

Reputation: 27

How do I break out of a loop while reading in a string?

For example:

Scanner keyboard = new Scanner(System.in);  
int counter=1;
while (!(keyboard.equals('0')))
{
    for (int i=1;i<=counter;i++)
    {
        prodNum[i]=keyboard.nextInt();
        quantity[i]= keyboard.nextInt();
    }   
    counter++;
}

How do I break out of a loop when I enter in a zero? I can't seem to figure it out. It keeps taking input, even when I enter a zero? I need for it keep taking input until the user enters a zero.

Any ideas what I'm doing wrong?

Upvotes: 2

Views: 260

Answers (2)

NeilZhang
NeilZhang

Reputation: 1

    int counter=1;
    int flag = 1; 
    while (flag != 0)
    {
        for (int i=1;i<=counter;i++)
        {
            if(flag == 0)
            {
                break;
            }
            prodNum[i]=keyboard.nextInt();

            quantity[i]= keyboard.nextInt();

            flag = quantity[i];

        }   
        counter++;
    }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727027

keyboard.equals('0') will compile, but it is never going to evaluate to true, because Scanner object cannot possibly be equal to a Character object.

If you would like to wait for the scanner to return zero to you, you should call next() or nextLine() on it, and compare the resultant String object to "0".

while (true) {
    while (keyboard.hasNext() && !keyboard.hasNextInt()) {
        System.out.println("Please enter an integer value.");
        keyboard.nextLine();
    }
    if (!keyboard.hasNextInt())
        break;
    prodNum[i]=keyboard.nextInt();
    if (prodNum[i] == 0)
        break;
    while (keyboard.hasNext() && !keyboard.hasNextInt()) {
        System.out.println("Please enter an integer value.");
        keyboard.nextLine();
    }
    if (!keyboard.hasNextInt())
        break;
    quantity[i]=keyboard.nextInt();
    if (quantity[i] == 0)
        break;
    i++;
}

Demo.

Upvotes: 1

Related Questions