BigC
BigC

Reputation: 29

Breaking out of a loop

Im trying to break out of a loop, I just want to keep entering numbers until I enter 0, this is what I have but I can't seem to break it.

import javabook.*;

class loop {

    public static void main (String [] args) {

        MainWindow mWin = new MainWindow();
        InputBox iBox = new InputBox(mWin);

        int numbers = iBox.getInteger("");

        while (numbers > 0) {
            if (numbers > 0) {
                iBox.getInteger("EnterNumber");
            } else if (numbers == 0) {
                break;
            }
        }

    }

}

Upvotes: 0

Views: 1215

Answers (7)

m0skit0
m0skit0

Reputation: 25873

Useless break.

else if (numbers == 0){ break; }

is superfluous because the very same while condition will exit if numbers is 0. The other if is also superfluous. You can do the same thing with

while(numbers > 0){  
    iBox.getInteger("EnterNumber"); 
}

Just keep in mind this is an infinite loop since numbers will never change.

PS: get a good programming book/tutorial

Upvotes: 1

Viruzzo
Viruzzo

Reputation: 3025

Follow the suggestions, you will end up with this:

while (numbers > 0)
{
    numbers = iBox.getInteger("EnterNumber");
}

Upvotes: 1

Óscar López
Óscar López

Reputation: 235994

Maybe you should try this:

numbers = iBox.getInteger("EnterNumber");

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Try do-while:

int number;

do {
    number = iBox.getInteger("Enter number: ");
} while (number > 0); 

Upvotes: 2

Harv
Harv

Reputation: 523

You set the value of numbers once. When it is initialized, but you never assign another value to it. I think that this should work, but I have not tested it.

import javabook.*;
 class loop{
  public static void main (String [] args){

 MainWindow mWin = new MainWindow();
 InputBox iBox = new InputBox(mWin);

 int numbers = -1;

 while(numbers != 0){
    numbers = iBox.getInteger("EnterNumber");
}
}

}

Upvotes: 2

Paul Medcraft
Paul Medcraft

Reputation: 1406

Looks like you need to reassign numbers to the result of iBox.getInteger().

Try changing

iBox.getInteger("EnterNumber");

to

numbers = iBox.getInteger("EnterNumber");

Upvotes: 9

Peter Lawrey
Peter Lawrey

Reputation: 533492

If you step through your code in a debugger, you would see you are not changing numbers inside your while loop, so it will never exit.

Upvotes: 1

Related Questions