[英]Java: Try-Catch statement within a Do-While loop
我正在尝试执行一些扫描用户输入值的代码。 这个动作包含在我写的自定义方法中,名为getTriangleDim(); 该方法读入users int值,确保它在某个范围内,然后返回输入的int值。 该方法效果很好,我没有任何问题。
当我为getTriangleDim()方法输入非int值时出现问题。 它给我一个InputMismatchException错误。 我已经在do-while循环中编写了一个try-catch语句来尝试修复此问题。 但这是我第一次使用try-catch语句,而我显然错过了一些东西。
以下是嵌套在do-while循环中的try-catch语句的代码:
//loop to scan for triangle dimension
boolean bError = true;
int triangle;
do{
try {
triangle = getTriangleDim();
bError=false;
}
catch (Exception e){
System.out.println("You did not enter an integer, please enter an integer value");
triangle = getTriangleDim();
}
}while (bError);
如果我通过输入一个char值代替int来测试它,它实际捕获错误一次,然后打印我的“你没有.....”语句。 但是如果我重新输入另一个非int数字,我再次得到一个运行时错误,说.......你猜对了........ InputMismatchException错误。
我的方法的代码在这里:
//method for scanning triangle dimensions from keyboard
public static int getTriangleDim(){
int triangle = 0;
Scanner keyboard = new Scanner(System.in);
do{
System.out.print("Enter a non-zero integer length (+/-1 - +/-16): ");
triangle = keyboard.nextInt();
if((!(triangle <= 16 && triangle >= 1))&&(!(triangle >= -16 && triangle <= -1)))
System.out.println("Inpute value outside of range");
}while((!(triangle <= 16 && triangle >= 1))&&(!(triangle >= -16 && triangle <= -1)));
return triangle;
}
我需要Do-While循环继续,但我不断收到这些错误。
没有必要在catch
块中请求输入。 你已经处于循环中,所以你可以捕获异常,告诉用户给你有效的输入,然后你不需要做任何其他的事情 - 你会回到开头。
do{
try {
triangle = getTriangleDim();
bError=false;
} catch (Exception e){
System.out.println("You did not enter an integer, please enter an integer value");
// Don't do anything else in here: we will loop back to the beginning again and get new input!
}
}while (bError);
作为旁注(正如您已经注意到的),如果您尝试在该try
块之外使用triangle
,则您的代码当前不会编译,因为"triangle might not have been initialized"
。 这是因为编译器无法在编译时确定程序在运行时将执行的操作 :也就是说,编译器无法看到该triangle
将始终在该循环内初始化。 所以你的变量声明也应该将triangle
设置为某个默认值。 0
是int
的正常默认值,但是在程序中使用任何有意义的东西(看起来0
很好,基于你的getTriangleDim
代码)。
int triangle = 0;
do { // etc.
通过这种方式,您可以“保证”编译器在您离开循环时triangle
将具有值,并且您将能够在其他地方使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.