【发布时间】:2023-03-11 18:10:01
【问题描述】:
我正在制作的控制台程序中出现错误,我似乎无法处理其中的错误。
如果用户输入了不正确的输入类型(例如 int 所在的浮点数),他们会受到谴责,并且程序会运行(即使程序关闭,它也会以 my 的方式执行):
while(!scanner.hasNextLong()){
System.out.println("You entered something bad.. Why do you hurt me?");
System.out.println("*Calcumatastic dies, and I hope you feel remorseful*");
try {
Thread.sleep(4000);
} catch (InterruptedException f) {
f.printStackTrace();
}
System.exit(0);
}
例如,如果用户输入一个零作为不能等于零的变量(由于除零),则用户会受到谴责,但生活仍在继续,程序仍然可以运行:
while (b == 0) {
System.out.println("Did you even read the instructions?? You cannot divide by zero!");
System.out.println();
System.out.println("Second Integer: ");
b = scanner.nextLong();
}
但是,如果用户尝试除以零,则输入错误的输入类型,程序会崩溃。我究竟做错了什么?我已经尝试过像在其他情况下那样进入 try/catch-while 循环,但它似乎没有奏效:
System.out.println("Second Integer: ");
while(!scanner.hasNextLong()){
System.out.println("You entered something bad.. Why do you hurt me?");
System.out.println("*Calcumatastic dies, and I hope you feel remorseful*");
try {
Thread.sleep(4000);
} catch (InterruptedException f) {
f.printStackTrace();
}
System.exit(0);
}
b = scanner.nextLong();
while (b == 0) {
System.out.println("Did you even read the instructions?? You cannot divide by zero!");
System.out.println();
System.out.println("Second Integer: ");
b = scanner.nextLong();
}
【问题讨论】:
-
“崩溃”是什么意思?您是否收到异常和堆栈跟踪?
标签: java error-handling