while循环中的try-catch方法?

我有这个代码,我想把try-catch放在while循环中。 逻辑是,“当存在输入错误时,程序将继续要求正确的输入”。 我该怎么做? 提前致谢。

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

这里我使用了breakcontinue关键字。

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

你可以添加break; 作为try块中的最后一行。 这样,如果抛出任何execption,控制将跳过break并进入catch块。 但是如果没有抛出exception,程序将运行到break语句,该语句将退出while循环。

如果这是唯一的条件,那么循环应该看起来像while(true) { ... }

你可以只有一个布尔标志,你可以适当地翻转。

下面的伪代码

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

在你的catch块中写'continue;' 🙂