如果抛出了例外,那么程序可以继续执行并获取用户的输入?
我最近刚刚了解到了尝试/捕获块,以及一旦投放计划将如何退出。在代码下面的照片中,一旦用户输入“ A”而不是随机数,就会捕获投影。
用户有什么办法可以重新进入该值而不会再次投放投影?
import java.util.Scanner
public class user_Num {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int random_Num = 0;
try {
System.out.println("Enter a random number:");
random_Num = input.nextInt();
if (random_Num > 0) {
System.out.println("The user entered a number that is positive.");
} else if (random_Num<0) {
System.out.println("The user entered a number that is negative");
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
System.out.println("Enter a random number:");
random_Num = input.nextInt();
System.out.println("User Input Taken.");
}
}
程序结果:
I just recently learned about the try/catch block and how once the expection is thrown the program will exit. In the photo below the code the Expection is caught once the user enters "a" instead of a random number.
Is there any way the user could reenter the value without the Expection being thrown again?
import java.util.Scanner
public class user_Num {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int random_Num = 0;
try {
System.out.println("Enter a random number:");
random_Num = input.nextInt();
if (random_Num > 0) {
System.out.println("The user entered a number that is positive.");
} else if (random_Num<0) {
System.out.println("The user entered a number that is negative");
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
System.out.println("Enter a random number:");
random_Num = input.nextInt();
System.out.println("User Input Taken.");
}
}
Program Result:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这很容易,您只需要恢复捕获块中的整个代码即可。您也可以有一个线程。
Yeah this is pretty easy you just have to revert back to whole code in the catch block. You could also have a thread.