You have to assign repeat in your while-loop so it becomes false if the user says yes:

repeat = !input.equalsIgnoreCase("yes"); 
Answer from Jean Logeart on Stack Overflow
🌐
Coderanch
coderanch.com › t › 691813 › java › Loop-program-user-input
While-Loop for ending program from user input (Beginning Java forum at Coderanch)
March 17, 2018 - Putting the while loop at the very beginning isn't good either then telling the code to only run if userName is 'q' because it looks for the value of userName to see whether or not its 'q' for it to run, but userName hadn't been given a value yet until the user inputs something for it. But if I put the while loop after the program accepts a value from the user, when it loops, the part to prompt for userName isn't shown at all. ... This is a classic error and is why writing this is a no-no. You meant to say but as you found out, if you mistakenly leave out one of the '=' then the behavior changes entirely. You should instead use · JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
Discussions

java - How to end a For Loop via user input - Stack Overflow
can u help with this stopwatch? I want that after writting "0" program will end. Stopwatch is working but i dont now how to stop. Thank for your answer. package stopky; import java.util.Scanner; More on stackoverflow.com
🌐 stackoverflow.com
java - How to start and end a loop with user input? - Stack Overflow
I am having trouble figuring out how to prompt a question that allows for the user to enter a number or character to start or end a loop. The following is the code import java.util.Scanner; pub... More on stackoverflow.com
🌐 stackoverflow.com
How do I exit a while loop in Java? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Exit While Loop with String Input?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
8
0
December 17, 2021
🌐
W3Schools
w3schools.com › java › java_break.asp
Java Break and Continue
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement. The break statement can also be used to jump out of a loop.
🌐
Stack Overflow
stackoverflow.com › questions › 31344414 › how-to-start-and-end-a-loop-with-user-input
java - How to start and end a loop with user input? - Stack Overflow
Would you like to restart?"); } } // end Main public static int genRanInRange(int start, int end) { return (int)(Math.random()*(end-start+1.0)) + start; } // end genRanInRange } // end Dice Roller ... An if condition is not a loop. It's a branch. As a matter of fact, your code doesn't contain any loop at all. ... Put the rest of the code in a while loop. and have there be a boolean defined at the beginning as true for the first loop, and then compare UserResp to Y or N to set the boolean. ... Sign up to request clarification or add additional context in comments. ... import java.util.Scanner;
🌐
Programiz
programiz.com › java-programming › break-statement
Java break Statement (With Examples)
This means when the user input negative numbers, the while loop is terminated. In the case of nested loops, the break statement terminates the innermost loop. ... Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.
Find elsewhere
🌐
Reddit
reddit.com › r/javahelp › exit while loop with string input?
r/javahelp on Reddit: Exit While Loop with String Input?
December 17, 2021 -

I am trying to create a program which prompts the user for a word, and computes the number of words entered with a String Length that is less than 5. I am using a while loop for this and my hope is that the I can exit the loop after entering string with value 5 or higher or something that isn't a string. Obviously, I cannot enter an int or double as it would be read as a String.

This is part of my code segment

Scanner in= new Scanner (System.in);

	int word\_length = 0;

	System.out.print("Please enter a word: "); 

	

	while (in.hasNext()) 

	{	

		System.out.print("Please enter a word: "); 

		String word = in[.next](https://scan.next)(); 

		

		if(word.length()< 5) 

		{

word_length++;

		}

		

		else

		{

System.out.println("The amount of words entered with less than 5 characters is: "+word_length);

		}

		

	}

______________________________________________

The problem with this is the loop is not exited because the condition still is not false (input remains a String). So the console reads the statement and prompt when I enter something with 5 or more characters. How can I exit this loop and just print out the statement which gives the number of words entered that have less than 5 characters?

Top answer
1 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 3
1
Your "while (in.hasNext()) {}" will always be true in this scenario because you are using the Scanner on System.in. Look into while (true) {} and break.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 226257 › stop-a-loop-at-input-of-character
java - Stop a Loop at input of Character | DaniWeb
DataAnalyzer { public static void ... validate tokens for you. Keep consuming values while the next token is a double; the moment the user types a letter (or anything non‑numeric), the loop ends....
🌐
Tutorialspoint
tutorialspoint.com › java › java_break_statement.htm
Java - break Statement
The Java break statement is used to exit a loop immediately and transfer control to the next statement after the loop.
🌐
Baeldung
baeldung.com › home › java › java io › read user input until a condition is met
Read User Input Until a Condition Is Met | Baeldung
January 8, 2024 - As the code above shows, the readUserInput method reads user input from System.in and stores the data in the userData List. Once we receive “bye” from the user, we break the infinite while loop.
🌐
YouTube
youtube.com › watch
How to End an Infinite While Loop with User Input in Java - YouTube
Learn how to effectively manage infinite loops in Java with user input, allowing for a dynamic loading sequence that can be interrupted by the press of the e...
Published   March 23, 2025
Views   1
Top answer
1 of 4
3

You should try to use "a real termination condition" in order to terminate a while loop (or any loop for that matter); it's cleaner and should be easier to understand by everyone else.

In your case, I think it's better to have a do-while loop with some condition around this logic: num % 2 == 0, and an inner while loop for handling user input/validation.

If you still want to break loops abruptly, have a look here.

If you still need some help with the code, hit me up and I'll sketch up something.

2 of 4
1

I did not follow the conditions you wanted exactly because it does not make sense to have a continue condition AND a terminate condition unless there are other options.

What did you want the user to do if he entered 3, 4 or 5? Exit the code or continue the code? Well if the default is to exit, then you do not need the code to exit on 2 because it already will! If the default is to continue, then you do not need the continue on 1 and only the exit on 2. Thus it is pointless to do both in this case.

Here is the modified code to use a do while loop to ensure the loop is entered at least 1 time:

    int x;
    do {
        System.out.println("Enter a number to check whether or not it is odd or even");
        Scanner s = new Scanner(System.in);
        int num = s.nextInt();
        if (num % 2 == 0)
            System.out.println("The number is even");
        else 
            System.out.println("The number is odd");
        //trying to figure out how to get the code to terminate if you put in a value that isn't a number
        System.out.println("Type 1 to check another number, anything else to terminate.");

        if (!s.hasNextInt()) {
            break;
        }
        else {
            x = s.nextInt();
        }
    } while(x == 1);
   }

Note that I added a check to !s.hasNextInt() will check if the user enters anything other than an int, and will terminate without throwing an Exception in those cases by breaking from the loop (which is the same as terminating the program in this case).

If the x is a valid integer, then x is set to the value and then the loop condition checks if x is 1. If x is not 1 the loop terminates, if it is it will continue through the loop another time.

🌐
Delft Stack
delftstack.com › home › howto › java › exit while loop in java
How to Exit a While Loop in Java | Delft Stack
February 2, 2024 - Java uses a return-statement to return a response to the caller method, and control immediately transfers to the caller by exiting a loop(if it exists). So we can use return to exit the while-loop too.