How to exit Java loop? While-loop in a basic guessing game

拈花ヽ惹草 提交于 2019-12-01 17:10:56

You can use break to get out of the current loop.

for (int i = 0; i < 10; i++) {
  if (i > 5) {
    break;
  }
  System.out.Println(i);
}

Prints:

0
1
2
3
4
5

However, a do-while loop is probably better for your use case.

Change

while(true){
  //At some point you'll need to 
  //exit the loop by calling the `break` key word
  //for example:

  if(/*it's not compatible with your condition*/)
    break;
}

to

boolean userWantsToPlay=true;
do{
   //the same as before
} while (userWantsToPlay);

then ask the user somewhere if they still want to play and set this variable to false if not.

The other solution is to keep your code as it is and just call break; after you ask the user and they say they don't want to continue, this just jumps out of the current loop and resumes at the first point after the loop. This is less preferred because it can be harder to trace the program flow as you read the code, especially if you start to have nested loops or multiple break points.

You can change while(true) statement with do while statement.

Scanner k= new Scanner(System.in);

do{
// do sth here...

//ask to user for continue or exit
System.out.println("Continue/Break");
String answer = k.next();

}while(answer.equals("Continue"));

If you want to exit the loop you can use break statement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!