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();
        }
    }
}
2
  • 1
    You program gets stuck in the inner loop and never gets a chance to read user input. Commented May 3, 2015 at 9:50
  • 1
    possible duplicate of Breaking out of nested loops in Java Commented May 3, 2015 at 10:37

1 Answer 1

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.