How do I exit a while loop in Java?
Use break
:
while (true) {
....
if (obj == null) {
break;
}
....
}
However, if your code looks exactly like you have specified you can use a normal while
loop and change the condition to obj != null
:
while (obj != null) {
....
}
How to manually exit a while loop (java)
In java String comparison is using equals function "==" might not work
Change
if (bad_input == "x") {
loop = false;
return;
}
To
if (bad_input.equals("x")) {
loop = false;
return;
}
How to exit a while loop after a certain time?
long startTime = System.currentTimeMillis(); //fetch starting time
while(false||(System.currentTimeMillis()-startTime)<10000)
{
// do something
}
Thus the statement
(System.currentTimeMillis()-startTime)<10000
Checks if it has been 10 seconds or 10,000 milliseconds since the loop started.
EDIT
As @Julien pointed out, this may fail if your code block inside the while loop takes a lot of time.Thus using ExecutorService would be a good option.
First we would have to implement Runnable
class MyTask implements Runnable
{
public void run() {
// add your code here
}
}
Then we can use ExecutorService like this,
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new MyTask()), 10, TimeUnit.SECONDS); // Timeout of 10 seconds.
executor.shutdown();
Break while loop inside for loop Java
use the break statement inside the if condition and set a boolean value to a variable.check for the status of that boolean variable just after the for loop ends.if its true then use a break statement to break out of the while loop.
while (!(list.contains("NORTH SOUTH") || list.contains("SOUTH NORTH") || list.contains("WEST EAST") || list.contains("EAST WEST"))) {
boolean conditionChecker=false;
for (int i = 0; i < list.size(); i++) {
for (int k = i + 1; k < list.size(); k++) {
if (list.get(i).contains("NORTH") && list.get(k).contains("SOUTH") ||
list.get(i).contains("SOUTH") && list.get(k).contains("NORTH") ||
list.get(i).contains("WEST") && list.get(k).contains("EAST") ||
list.get(i).contains("EAST") && list.get(k).contains("WEST")) {
list.remove(i);
list.remove(k - 1);
conditionChecker=true;
break;
}
}
if(conditionChecker==true){
break;
}
}
How I stop the While loop after the 3rd invalid attempt?
Like Adam suggested, you'll need a counter, such as:
int attempt = 0;
while (hours < 0 || hours > 280) {
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
// do something if you reach the limit. The >= comparison is
// useless before attempt will never go over 4.
if(attempt == 3){
// notify the user that something wrong happened
System.out.println("Your error message here");
// exit the main function, further code is not processed
return;
}
}
I suggested a message print and returning. For your information, other options can be:
- throw an exception with
throw new MaxAttemptReachedException();
- exit the while loop but keep processing the following code with the
break;
instruction.
How to break a while loop from an if condition inside the while loop?
The break
keyword does exactly that. Here is a contrived example:
public static void main(String[] args) {
int i = 0;
while (i++ < 10) {
if (i == 5) break;
}
System.out.println(i); //prints 5
}
If you were actually using nested loops, you would be able to use labels.
Exit while loop in java that has switch case?
You need to read input (int choice = input.nextInt();
) inside the while loop. Otherwise choice
never changes.
int i = 1;
while(i == 1)
{
int choice = input.nextInt();
switch(choice)
{
case 1:
System.out.println("Add");
break;
case 2:
System.out.println("Edit");
break;
case 3:
System.out.println("Delete");
break;
case 4:
System.out.println("Search");
break;
case 5:
i = 2;
break;
default:
System.out.println("Invalid Choice .. Try Again.");
}
}
How to stop while loop without break and exit in java
I would not consider it good code, but for the sake of it (and because most interview questions have weird answers anyway), you could wrap the whole loop in a try-catch
and throw an Exception
inside the loop.
Or skip the catch block and throw a RuntimeException
if the program execution does not need to continue.
Related Topics
Value Change Listener for Javafx's Textfield
How to Stop the Task Scheduled in Java.Util.Timer Class
Best Way to Create a Hashmap of Arraylist
How to Run All Tests Belonging to a Certain Category in Junit 4
Unsatisfiedlinkerror: No Opencv_Java249 in Java.Library.Path
Org.Openqa.Selenium.Webdriverexception: Unknown Error: Call Function Result Missing 'Value'
Which Swing Component Methods Are Thread Safe
Efficiently Finding the Intersection of a Variable Number of Sets of Strings
Remove Duplicates from Arraylists
Spring Choose Bean Implementation at Runtime
Difference Between an Unbound Wildcard and a Raw Type
Making Spring-Data-Mongodb Multi-Tenant
How to Inject Module Declaration into Jar