简体   繁体   中英

A try-catch method in while loop?

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


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

}

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

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;' :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM