[英]A try-catch method in while loop?
我有这段代码,我想将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());
}
}
boolean gotCorrect = false;
while(!gotCorrect){
try{
//your logic
gotCorrect = true;
}catch(Exception e){
continue;
}
}
在这里,我使用了break and Continue关键字。
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;
}
}
您可以添加break;
作为try
块的最后一行。 这样,如果引发任何执行,控制将跳过该break
并移入catch
块。 但是如果没有抛出异常,程序将运行到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;'
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.