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 OverflowYou have to assign repeat in your while-loop so it becomes false if the user says yes:
repeat = !input.equalsIgnoreCase("yes");
You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you :
if ("yes".equals(input))
repeat = true; // This would continue the loop
else
repeat = false; // This would break the infinite while loop
java - How to end a For Loop via user input - Stack Overflow
java - How to start and end a loop with user input? - Stack Overflow
How do I exit a while loop in Java? - Stack Overflow
Exit While Loop with String Input?
Videos
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?
For more readable code you can use a boolean variable and assign it to true according to your input equals to "y" condition
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean stopFlag= false;
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
String userInput =input.next();
if(!userInput.equals("y"))
stopFlag=true;
}while (!stopFlag);
}
You can do this:
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String temp = input.next();
if(temp.equals("y")) {
// if you need to do something do it here
continue; // will go to the next iteration
} else if(temp.equals("n")) {
break; // will exit the loop
}
}
break; is what you need to break out of any looping statement like for, while or do-while.
In your case, its going to be like this:-
for(int x = 10; x < 20; x++) {
// The below condition can be present before or after your sysouts, depending on your needs.
if(x == 15){
break; // A unlabeled break is enough. You don't need a labeled break here.
}
System.out.print("value of x : " + x );
System.out.print("\n");
}
If for some reason you don't want to use the break instruction (if you think it will disrupt your reading flow next time you will read your programm, for example), you can try the following :
boolean test = true;
for (int i = 0; i < 1220 && test; i++) {
System.out.println(i);
if (i == 20) {
test = false;
}
}
The second arg of a for loop is a boolean test. If the result of the test is true, the loop will stop. You can use more than just an simple math test if you like. Otherwise, a simple break will also do the trick, as others said :
for (int i = 0; i < 1220 ; i++) {
System.out.println(i);
if (i == 20) {
break;
}
}
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.
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.
The loop should not write to an in-memory buffer, but to the file writer directly (wrapped inside a BufferedWriter). This will avoid running out of memory.
You should start a new thread which executes your while loop, and tests at each iteration if the thread has been asked to interrupt itself, using Thread.currentThread().isInterrupted(). Once interrupted, the thread should stop the while loop, and close the writer.
Have your main thread read from the command line, and when the stop command is entered, call interrupt() on the writer thread.
When you bring "Infinity" into picture, YES things are going to run out of memory at some point.
To exit a loop, you can have it running in a separate thread and let the main thread listen to the user inputs. And based on the input, the main thread will alter a shared variable, usually a boolean to determine an end.
Your condition is always true. If you want to react to a user typing in "quit" while entering a new guess, you can do it with an infinite loop and a break, like this:
while (true) {
System.out.println("Please every a word or QUIT to exit");
String guess = input.nextLine();
if (quit.equalsIgnoreCase(guess)) {
break;
}
for(int i = 0; i < words.length; i++) {
...
}
}
Your loop while will keep going until you change your String quit to something other than "quit". Here is an example:
while(quit.equals("quit")) {
System.out.println("Please every a word or QUIT to exit");
String guess = input.nextLine();
for(int i = 0; i < words.length; i++)
{
if(guess.equals(words[i]))
{
System.out.println("That word is spelled correctly.");
}
if(guess.equals("quit") {
quit = "something_else";
}
else
{
System.out.println("That word is not spelled correctly.");
System.out.println("Would you like to add it to the dictionary? (Y/N)");
}
}
}