实施 try/catch 块

implementing a try/catch block

所以我正在研究一个使用 try/catch 块来捕捉的猜数游戏(这是作业)。如果用户输入非整数值或低于或高于给定范围(在本例中为 1-10)的数字。

但是我在放置 try catch 块时遇到了问题 understanding/properly 我读过它是如何工作的,但是当我尝试将它实现到我的简单代码中时,它似乎被忽略了。

这是代码

//import statements
import java.util.*;     //for scanner class


// class beginning
class  Guess {
    public static void main(String[] args ) { 
        //Declare variables area

        int secretNumber, guess;

        secretNumber = (int) (Math.random() * 10 + 1);           

        Scanner keyboard = new Scanner(System.in);


        // beginning message to user to explain the program
        System.out.println("Welcome to my guess a number program!");
        System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");   

        //Collect inputs from user or read in data here

        System.out.println("Enter a guess (1-10): ");
        try {
            guess = keyboard.nextInt();
            if (guess < 1 || guess > 10){
            }
        } catch (InputMismatchException e) {
            guess= keyboard.nextInt();
            System.out.println("Not a valid integer");
        }
        //Echo input values back to user here



        //main code and calculations to do
        do {

            if (guess < 1 || guess > 10) {
                System.out.println("Your guess is not in the corre try again.");
                guess = keyboard.nextInt();
            }
            if (guess == secretNumber) {
                System.out.println("Your guess is correct. Congratulations!");
                guess = keyboard.nextInt();
            } else if (guess < secretNumber) {
                System.out
                        .println("Your guess is smaller than the secret number.");
                guess = keyboard.nextInt();
            } else if (guess > secretNumber) {
                System.out
                        .println("Your guess is greater than the secret number.");
                guess = keyboard.nextInt();
            }
        } while (guess != secretNumber);


        //End program message
        System.out.println();
        System.out.println("Hope you enjoyed using this program!");
    }// end main method 


}// end class

猜对数字时不显示"Your guess is correct. Congratulations!"

我是否正确地实现了 try catch 块?如果不是,我该如何解释,所以我可以做第二个,它捕获浮点数、字符串和任何不是 int 的东西。

它的作用

编辑 下面是更新后的代码,我现在遇到的唯一问题是,如果用户只是按 enter 键而没有输入任何内容,我无法弄清楚如何应用另一个 catch 我假设我需要从用户那里获取输入并将其转换为一个字符串然后比较?

    //import statements
import java.util.*;     //for scanner class


 // class beginning
public class Guess {
public static void main(String[] args ) {
    //Declare variables area
    int guess, secretNumber =  (int) (Math.random() * 10 + 1), lowGuess,highGuess;
    Scanner keyboard = new Scanner(System.in);

    // beginning message to user to explain the program
    System.out.println("Welcome to my guessing number program!");
    System.out.println("Please enter in a number to start guessing(enter in a number between 1-10): ");

    //main code and calculations to do
    guess = 0;
    lowGuess = 0;
    highGuess = 11;
    do {
        try {
            guess = keyboard.nextInt();
            if (guess < 1 || guess >10){
                System.out.println("Your guess is not in the correct range try again.");
            }
            else if(guess == secretNumber){
                System.out.println("Your guess is correct. Congratulations!");
            }
            else if(guess < secretNumber && guess <= lowGuess){
                System.out.println("The number you entered is either the same entered or lower please re-enter");
            }
            else if (guess < secretNumber && guess > lowGuess){
                lowGuess = guess;
                System.out.println("Your guess is smaller than the secret number.");
            }
            else if ( guess > secretNumber && guess >= highGuess ){
                System.out.println("The number you entered is either the same entered or higher please re-enter");
            }
            else if (guess > secretNumber && guess < highGuess){
                highGuess = guess;
                System.out.println("Your guess is greater than the secret number.");
            }
        } catch (InputMismatchException e) {
            System.out.println("Not a valid input please re-enter");
            keyboard.next();
            guess = 0;
        }
    } while (guess != secretNumber);

    //End program message
    System.out.println();
    System.out.println("Hope you enjoyed using this program!");
}// end main method


}// end class

这是另一种方法,但使用了异常。请阅读 this page 以了解 try/catch 块的工作原理。

//import statements
import java.util.*;     //for scanner class


// class beginning
class  Guess {
public static void main(String[] args ) { 
//Declare variables area
int secretNumber, guess;

secretNumber = (int) (Math.random() * 10 + 1);

Scanner keyboard = new Scanner(System.in);


// beginning message to user to explain the program
System.out.println("Welcome to my guess a number program!");
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");

//Collect inputs from user or read in data here


//main code and calculations to do
do {


  System.out.println("Enter a guess (1-10): ");
  try {
    guess = keyboard.nextInt();
    if (guess < 1 || guess > 10){
      throw new Exception("Number must be  between 1 and 10");
    }else if(guess == secretNumber){
   throw new Exception("YOU WIN");
  }
  else if (guess < secretNumber){
   throw new Exception("NUMBER IS +");
  }
  else if (guess > secretNumber){
  throw new Exception("NUMBER IS -");
  }
} catch (InputMismatchException e)
{
  System.println("mustbeanumber");
}
catch(Exception e)
{
 System.out.println(e.getMessage());
}

} while (guess != secretNumber);


//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method 


}// end class` 

你想在这里做什么?

if (guess < 1 || guess > 10) {
}

你应该尝试这样的事情:

public class Guess {
    static int guess, secretNumber =  (int) (Math.random() * 10 + 1);
    static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args ) { 
        do {
            try {       
                guess = keyboard.nextInt();
                if (guess < 1 || guess >10){
                    System.out.println("Your guess is not in the corre try again.");
                }
                if(guess == secretNumber){
                    System.out.println("Your guess is correct. Congratulations!");
                }
                else if (guess < secretNumber){
                    System.out.println("Your guess is smaller than the secret number.");
                }
                else if (guess > secretNumber){ 
                    System.out.println("Your guess is greater than the secret number.");                                     
                }
            } catch (InputMismatchException e) {
                System.out.println("Not a valid integer");
            }
        } while (guess != secretNumber);
    }
}

编辑:您必须在 try 块的范围内放置一段可能会引发异常的代码。知道将代码的哪一部分放入 try 块中是最先进的技术(不要太多也不要太少)。

in-between the try and catch you have your main code/calculations to do and then you close it off and end with the catch to see if after all that if what was entered was valid?

你总是可以像你在这里所说的那样在顶层捕获异常,但实际上这不是这样做的方法。因为当异常发生而你没有捕获它时,会有一个过程称为堆栈展开。

了解堆栈展开的工作原理对于理解正在发生的事情非常重要。

您可以在此处找到有关此过程如何工作的信息:Explanation of stack unwinding。它解释了 C++ 中的堆栈展开,但我希望它在 Java.

中(完全)相同