A try-catch method in while loop?

孤街浪徒 提交于 2019-12-04 18:46:17
Chandra Sekhar

Here I have used break and continue keyword.

while(true) {
    try {
        System.out.print("Enter your guess: ");
        g = input.nextInt();
        if (g == a) {

            System.out.println("**************");
            System.out.println("*  YOU WON!  *");
            System.out.println("**************");
            System.out.println("Thank you for playing!");

        } else if (g != a) {
            System.out.println("Sorry, better luck next time!");
        }
        break;
    } catch (InputMismatchException e) {
        System.err.println("Not a valid input. Error :" + e.getMessage());
        continue;
    }
}
boolean gotCorrect = false;
while(!gotCorrect){
  try{
    //your logic
    gotCorrect = true;
  }catch(Exception e){
     continue;
  }

}

You can add a break; as the last line in the try block. That way, if any execption is thrown, control skips the break and moves into the catch block. But if not exception is thrown, the program will run down to the break statement which will exit the while loop.

If this is the only condition, then the loop should look like while(true) { ... }.

You could just have a boolean flag that you flip as appropriate.

Pseudo-code below

bool promptUser = true;
while(promptUser)
{
    try
    {
        //Prompt user
        //if valid set promptUser = false;
    }
    catch
    {
        //Do nothing, the loop will re-occur since promptUser is still true
    }
}

In your catch block write 'continue;' :)

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