A try-catch method in while loop?

我的梦境 提交于 2019-12-12 09:22:38

问题


I have this code, and I want to put the try-catch inside a while loop. The logic would be, "while there is an input error, the program would keep on asking for a correct input". How will I do that? Thanks in advance.

public class Random1 {

  public static void main(String[] args) {

    int g;

    Scanner input = new Scanner(System.in);
    Random r = new Random();
    int a = r.nextInt(10) + 1;


    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!");
        }
    } catch (InputMismatchException e) {
        System.err.println("Not a valid input. Error :" + e.getMessage());
    }


}

回答1:


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;
    }
}



回答2:


boolean gotCorrect = false;
while(!gotCorrect){
  try{
    //your logic
    gotCorrect = true;
  }catch(Exception e){
     continue;
  }

}



回答3:


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) { ... }.




回答4:


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
    }
}



回答5:


In your catch block write 'continue;' :)



来源:https://stackoverflow.com/questions/9781373/a-try-catch-method-in-while-loop

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