为什么我的程序打印出异常声明无休止地给用户输入错误?

时间:2015-07-08 20:13:11

标签: java exception exception-handling

我不知道我的标题是否合理,但这是代码©

import java.util.InputMismatchException;
import java.util.Scanner;
public class Gussing {
    public static void theGame(Scanner input){
        int randomNum= (int)(Math.random()*101);//randomizes a number between 0-100 inclusive of both
        System.out.println(randomNum); //for debugging purposes
        int attemptCounter = 0; //counts how many attempts the user make
        System.out.print("Welcome to the guess-the number game! Enter your guess: ");

        while(true){
            System.out.println("here is bad input");
            try{
                System.out.println("here is after the bad input");
                int userInput= input.nextInt();
                if (userInput==randomNum) //when usr input and generated random number are equal we print how many attempts
                {
                    attemptCounter++;
                    System.out.println("Congrats you made the right guess after "+ attemptCounter + " attempts!");
                    break;

                }

                if(userInput<randomNum){
                    attemptCounter++;
                    System.out.print("Too low! Try again: ");

                    }
                else {
                    attemptCounter++; //else clause does the opposite of if clause
                    System.out.print("Too high! Try again: ");

                    }


                }
            catch( Exception e){
                    System.out.println("Invalid input");

                    }
            }

    }
    public static void main(String[] args){
        Scanner input = new Scanner (System.in);
        theGame (input);


        System.out.println("Play again? (Y/N)");

        try{
            char answer=input.next().toLowerCase().charAt(0);



            //toLowerCase method so that N =n = no !

            if (answer =='y') theGame (input);


            else if (answer =='n') System.out.println("Good bye");


            input.close(); //no more input data

            }
        catch(Exception e){
            System.out.println("invalid input");
        }
    }


}

所以当用户键入错误的类型,即int时,它会输出invalid input。然而,这不是问题在于它无限地打印出来的问题。我尝试调整try catch块,但它根本没有帮助

1 个答案:

答案 0 :(得分:2)

nextInt不会从输入缓冲区中删除非整数数据,因此除非数据被消耗,否则它将无限期地被回收。在这种情况下,方法抛出InputMismatchException,因此您可以将异常块编写为

} catch (InputMismatchException e) {
    System.out.println("Invalid input " + input.nextLine());
}