简体   繁体   English

实现try / catch块

[英]implementing a try/catch block

So I am working on a guessing number game that uses a try/catch block to catch (this is homework). 因此,我正在研究一种使用try / catch块进行捕捉的猜数字游戏(这是家庭作业)。 If the user enters a non-integer value or a number that is below or above the given range (in this case 1-10). 如果用户输入非整数值或小于或大于给定范围的数字(在这种情况下为1-10)。

But I am having issues understanding/properly placing the try catch block I read on how it works but when I try to implement it into my simple code it just seems to be ignored. 但是我在理解/正确放置try catch块时遇到了问题,我阅读了它的工作原理,但是当我尝试将其实现到我的简单代码中时,它似乎只是被忽略了。

Here is the code 这是代码

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

It doesn't display "Your guess is correct. Congratulations!" 它不会显示"Your guess is correct. Congratulations!" when you guess the right number. 当您猜测正确的数字时。

Am I implementing the try catch block correctly? 我是否正确实现了try catch块? If not how do I and can it be explained so I can do the second one where it catches the float, string and anything not a int. 如果不是的话,我将如何解释它,所以我可以做第二个捕获浮点数,字符串和任何非int的东西。

what it does do 它做什么

  • it correctly randomizes from 1-10 正确地从1-10随机分配
  • the program does check to see if it is within the given range 程序会检查是否在给定范围内

EDIT below is the updated code my only issue I have with it now is that I can't figure out how to apply another catch if a user just hits enter without entering anything I assume I'd need to take the input from user turn it into a string then compare? 下面的EDIT是更新的代码,我现在唯一遇到的问题是,如果用户只是按回车键而不输入任何内容,我想不通如何应用另一个捕获,我想我需要从用户那里将其输入变成一个字符串然后比较?

    //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 is another approach, but using Exceptions. 这是另一种方法,但是使用异常。 Please, read this page to understand how try/catch block works. 请阅读此页面,以了解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` 

What do you want to do here ? 您想在这里做什么?

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

You should try something like this : 您应该尝试这样的事情:

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

EDIT : You have to put a piece of code which could maybe throw an exception, in the scope of the try block. 编辑:您必须在try块的范围内放置一段可能会引发异常的代码。 It is state of the art to know which part of the code to put in the try block (not too much nor too less). 知道将哪些部分代码放入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? 在try和catch之间,您需要执行主要代码/计算,然后关闭它并以catch结尾,以查看输入的内容是否有效?

You could always catch the exceptions at top level like you're saying here, but in practice that's not the way to do it. 您总是可以像在这里所说的那样在顶级捕获异常,但是实际上这并不是解决问题的方法。 Because when an exception occurs and you don't catch it there will be a process called stack unwinding. 因为当发生异常并且您没有捕获到异常时,会有一个称为堆栈展开的过程。

It's really important to understand how stack unwinding works in order to understand what's happening. 了解堆栈展开的工作原理以了解正在发生的事情非常重要。

You can find information about how this process works here : Explanation of stack unwinding . 您可以在此处找到有关此过程如何工作的信息: 堆栈展开的说明 It explains stack unwinding in C++ but I expect it to be (exactly) the same in Java. 它解释了C ++中的堆栈展开,但我希望它与Java中的(完全)相同。

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

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