简体   繁体   English

Java:Do-While循环中的Try-Catch语句

[英]Java: Try-Catch statement within a Do-While loop

I am trying to execute a bit of code that scans for a user input value. 我正在尝试执行一些扫描用户输入值的代码。 This action is contained in a custom method I wrote, named getTriangleDim(); 这个动作包含在我写的自定义方法中,名为getTriangleDim(); the method reads in the users int value, makes sure it is within a certain range, and then returns the int value that was entered. 该方法读入users int值,确保它在某个范围内,然后返回输入的int值。 The method works great and I have no issues with it. 该方法效果很好,我没有任何问题。

The problem arises when I enter a non-int value for my getTriangleDim() method. 当我为getTriangleDim()方法输入非int值时出现问题。 It gives me an InputMismatchException error. 它给我一个InputMismatchException错误。 I have written a try-catch statement into a do-while loop to attempt to fix this issue. 我已经在do-while循环中编写了一个try-catch语句来尝试修复此问题。 But this is the first time I have ever used a try-catch statement, and I am apparently missing something. 但这是我第一次使用try-catch语句,而我显然错过了一些东西。

Here is the code for the try-catch statement nested within the do-while loop: 以下是嵌套在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);

if i test it by entering a char value in place of the int, it actually catches the error once, and then prints my "you did not....." statement. 如果我通过输入一个char值代替int来测试它,它实际捕获错误一次,然后打印我的“你没有.....”语句。 But if I re-enter another non-int number, I get a runtime error again that says.......you guessed it........ InputMismatchException error. 但是如果我重新输入另一个非int数字,我再次得到一个运行时错误,说.......你猜对了........ InputMismatchException错误。

The code for my method is here: 我的方法的代码在这里:

//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;
    }

I need the Do-While loop to continue, but I keep getting these errors. 我需要Do-While循环继续,但我不断收到这些错误。

There's no need to ask for input in the catch block. 没有必要在catch块中请求输入。 You're already in a loop, so you can catch the exception, tell the user to give you valid input, and then you don't have to do anything else--you'll loop back around to the beginning. 你已经处于循环中,所以你可以捕获异常,告诉用户给你有效的输入,然后你不需要做任何其他的事情 - 你会回到开头。

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);

As a side note (and as you've noticed), your code won't currently compile if you try to use triangle outside of that try block, because "triangle might not have been initialized" . 作为旁注(正如您已经注意到的),如果您尝试在该try块之外使用triangle ,则您的代码当前不会编译,因为"triangle might not have been initialized" This is due to the fact that the compiler cannot determine at compile-time what your program will do at run-time : that is, the compiler cannot see that triangle will always be initialized within that loop. 这是因为编译器无法在编译时确定程序在运行时将执行的操作 :也就是说,编译器无法看到该triangle将始终在该循环内初始化。 So your variable declaration ought to also set triangle to some default value. 所以你的变量声明也应该将triangle设置为某个默认值。 0 is the normal default for int , but use whatever makes sense in your program (it looks like 0 is fine, based on your getTriangleDim code). 0int的正常默认值,但是在程序中使用任何有意义的东西(看起来0很好,基于你的getTriangleDim代码)。

int triangle = 0;
do { // etc.

This way you can "promise" the compiler that triangle will have a value by the time you leave the loop, and you'll be able to use it elsewhere. 通过这种方式,您可以“保证”编译器在您离开循环时triangle将具有值,并且您将能够在其他地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM