5 java exception-handling try-catch do-while inputmismatchexception
我正在尝试执行一些扫描用户输入值的代码.这个动作包含在我写的自定义方法中,名为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);
Run Code Online (Sandbox Code Playgroud)
如果我通过输入一个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;
}
Run Code Online (Sandbox Code Playgroud)
我需要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);
Run Code Online (Sandbox Code Playgroud)
作为旁注(正如您所注意到的),如果您尝试triangle在该块之外使用,您的代码当前将无法编译try,因为"triangle might not have been initialized". 这是因为编译器无法在编译时确定程序在运行时将执行的操作:也就是说,编译器无法看到triangle始终会在该循环内初始化。所以你的变量声明也应该设置triangle为一些默认值。0是 的正常默认值int,但请使用您的程序中有意义的任何内容(0根据您的getTriangleDim代码,它看起来很好)。
int triangle = 0;
do { // etc.
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以“承诺”编译器triangle在您离开循环时将获得一个值,并且您可以在其他地方使用它。
| 归档时间: |
|
| 查看次数: |
18055 次 |
| 最近记录: |