实现try / catch块

时间:2015-04-15 00:14:40

标签: java try-catch

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

但是我遇到了理解/正确放置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

        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。

它做了什么

  • 它正确地从1-10
  • 随机化
  • 程序会检查它是否在给定范围内

修改 下面是更新的代码我现在唯一的问题是,如果用户只是点击输入而没有输入任何东西我无法弄清楚如何应用另一个捕获我认为我需要从用户把它变成一个字符串然后比较?

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

2 个答案:

答案 0 :(得分:0)

这是另一种方法,但使用Exceptions。请阅读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` 

答案 1 :(得分:0)

你想在这做什么?

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块(不是太多也不太少)是最先进的。

  

在try和catch之间你有你的主要代码/计算   做然后你关闭它,然后用捕获结束,看看是否之后   如果输入的内容有效,那该怎么办?

你可以像往常一样在顶层捕捉异常,但实际上并不是这样做的。因为当发生异常并且你没有捕获它时,会有一个称为堆栈展开的进程。

理解堆栈展开是如何工作以了解正在发生的事情非常重要。

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