JAVA我不理解Try-catch

时间:2017-12-01 03:48:16

标签: java try-catch

这是我第一次来这里。我开始学习如何编码,所以老实说我希望这个问题不是我能在这里找到的东西! (我保证我搜索了一段时间,但由于我在这个主题中是一个菜鸟,为了解决我的疑问,我没有找到任何可以理解的东西。)

我在JAVA做一个简单的游戏,程序生成一个随机数,玩家必须猜测生成的数字。 当玩家输入一个数字时,游戏会显示一个提示,说明它是否高于或低于随机生成的数字。

如果只输入数字,程序本身可以正常工作,但我想添加一个try-catch语句来处理糟糕的用户输入。

我尝试使用我在代码中显示的语句,但我无法理解为什么它无法正常工作,因为当我输入不同数字的内容时,异常会被捕获并打印出来在控制台上运行System.out.println(),但程序在发生这种情况时终止。

我想尝试捕获只是为了在每次捕获异常时都不会在不终止程序的情况下输入数字。 我怎样才能解决这个问题?

非常感谢你的帮助!

import java.util.Scanner;

public class HiLo {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);  //Creates Scanner object to read from keyboard
        String playAgain = "";  //if == y, game restarts
        try {
            do {
                // Create a random number for the user to guess
                int theNumber = (int)(Math.random() * 100 + 1);
                //System.out.println(theNumber);        //Uncoment this in case we want to know the number (for testing).
                int guess = 0;  //Number entered by the player
                int count = 0;  //Number of tries of guessing the number
                while(guess != theNumber){
                    System.out.println("Guess a number between 1 and 100:");
                    guess = scan.nextInt(); //Reads the number typed on the keyboard by the player
                    count++;    //Plus 1 every time a number is entered
                    System.out.println("You entered " + guess +".");
                    if(guess < theNumber) { //If number entered is smaller
                        System.out.println("The number is bigger" + ", try again!");
                        System.out.println("Number of tries: " + count);
                    } else if(guess > theNumber) { //If number entered is bigger
                        System.out.println("The number is smaller" + ", try again!");
                        System.out.println("Number of tries: " + count);
                    } else {    //If both previous cases are false
                        System.out.println("Congratulations! You've found the number!");
                    }
                }
                //Once guess == theNumber
                System.out.println("Number of tries: " + count);
                System.out.println("Play again? (y/n)");
                playAgain = scan.next();    //Reads the String entered from keyboard by the player
            }
            while(playAgain.equalsIgnoreCase("y"));     //If player enters y, start again.
            //Otherwise
            System.out.println("Thank you for playing! Goodbye :)");
        } catch (Exception e) {
            System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
        }
        scan.close();   //Close scanner
    }   //Close main
}   //Close class

2 个答案:

答案 0 :(得分:1)

将try-catch放在while循环中并重新实现scan对象(scan = new Scanner(System.in)在catch块内。

@Override
public void onBackPressed() {

    HabitEventController hec = new HabitEventController(this);

    if(m != null && m.getPosition() != null){
        hec.setHabitEventLocation(heID, m.getPosition());
   }

   if(m == null || m.getPosition() == null){
       new AlertDialog.Builder(this)
               .setTitle("Really Exit?")
               .setMessage("Are you sure you want to exit, without creating a marker?")
               .setNegativeButton(android.R.string.no, null)
               .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int whichButton) {
                       dialog.dismiss();
                       MapsActivity.super.onBackPressed();
                   }
               }).show();
   }

//Remove this call because your app will close and crash before display the dialog
   // finish();
}

答案 1 :(得分:-1)

您需要了解try-catch块的工作原理。你不需要在try中包围整个代码。只需将导致异常的那部分代码放入。因此,在您的情况下,只需使用try环绕guess = scan.nextInt();,然后捕获异常。因为,当输入不是整数时,此语句引发异常。这样,您可以确保用户输入对while(guess != theNumber)循环的每次迭代都有效。

Edit_1: 我从您的代码中删除了try-catch块,并添加了以下&amp;它适用于我:

try{
  guess = scan.nextInt();} //Reads the number typed on the keyboard by the player
catch (InputMismatchException e){
  System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
  scan.nextLine();
  continue;
}