Java while 循环中的 try-catch 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9781373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A try-catch method in while loop?
提问by
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.
我有这个代码,我想把 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());
}
}
回答by Justin Pihony
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
}
}
回答by Nishant
boolean gotCorrect = false;
while(!gotCorrect){
try{
//your logic
gotCorrect = true;
}catch(Exception e){
continue;
}
}
回答by Shaunak
In your catch block write 'continue;'
:)
在您的 catch 块中写入'continue;'
:)
回答by Chandra Sekhar
Here I have used breakand continuekeyword.
在这里我使用了break和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;
}
}
回答by Ken Wayne VanderLinde
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.
您可以添加 abreak;
作为try
块中的最后一行。这样,如果抛出任何执行,控制将跳过break
并移动到catch
块中。但是如果没有抛出异常,程序将运行到break
将退出while
循环的语句。
If this is the only condition, then the loop should look like while(true) { ... }
.
如果这是唯一的条件,则循环应如下所示while(true) { ... }
。