0

i'm a newbie to java so i decided to create a simple program that prints out even numbers. I tried to make it exit a while loop if you answered no to the question but it just keeps on going.

Here's the code

public static void main(String[] args){
    String continueYorN = "Y";
    int i = 0;
    while (continueYorN.equalsIgnoreCase("y")){

        while(i >= 0){
            i++;
            if((i%2) == 0){
                System.out.println(i);
                continue;
            }
            System.out.println("Do you want to generate another even number?");
            continueYorN = userInput.nextLine();
        }
    }
}
daphshez
  • 9,272
  • 11
  • 47
  • 65
ramsesdv
  • 3
  • 1
  • 1
    You program gets stuck in the inner loop and never gets a chance to read user input. – Giorgio May 03 '15 at 09:50
  • 1
    possible duplicate of [Breaking out of nested loops in Java](http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java) – gnat May 03 '15 at 10:37

1 Answers1

1

Your loop has no break condition (i.e, something that stop the loop in some condition), so it will continue forever.

You should replace the inner while with something like that:

while(i >= 0){
        i++;
        if((i%2) == 0){
            System.out.println(i);
            break;
    }
yoni
  • 1,164
  • 2
  • 13
  • 29