Java accepting only numbers from user with Scanner

2019-09-02 10:42发布

I am trying to understand how to only accept numbers from the user, and I have attempted to do so using try catch blocks, but I would still get errors with it.

    Scanner scan = new Scanner(System.in);

    boolean bidding;
    int startbid;
    int bid;

    bidding = true;

    System.out.println("Alright folks, who wants this unit?" +
            "\nHow much. How much. How much money where?" );

    startbid = scan.nextInt();

try{
    while(bidding){
    System.out.println("$" + startbid + "! Whose going to bid higher?");
    startbid =+ scan.nextInt();
    }
}catch(NumberFormatException nfe){

        System.out.println("Please enter a bid");

    }

I am trying to understand why it is not working.

I tested it out by inputting a into the console, and I would receive an error instead of the hopeful "Please enter a bid" resolution.

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Auction.test.main(test.java:25)

3条回答
We Are One
2楼-- · 2019-09-02 11:03

The message is pretty clear: Scanner.nextInt() throws an InputMismatchException, but your code catches NumberFormatException. Catch the appropriate exception type.

查看更多
SAY GOODBYE
3楼-- · 2019-09-02 11:08

While using Scanner.nextInt(), it causes some problems. When you use Scanner.nextInt(), it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a Scanner.nextLine(). You can discard the result.

It's for this reason that I suggest always using nextLine (or BufferedReader.readLine()) and doing the parsing after using Integer.parseInt(). Your code should be as follows.

        Scanner scan = new Scanner(System.in);

        boolean bidding;
        int startbid;
        int bid;

        bidding = true;

        System.out.print("Alright folks, who wants this unit?" +
                "\nHow much. How much. How much money where?" );
        try
        {
            startbid = Integer.parseInt(scan.nextLine());

            while(bidding)
            {
                System.out.println("$" + startbid + "! Whose going to bid higher?");
                startbid =+ Integer.parseInt(scan.nextLine());
            }
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("Please enter a bid");
        }
查看更多
孤傲高冷的网名
4楼-- · 2019-09-02 11:08

Try catching the type of exception thrown rather than NumberFormatException (InputMismatchException).

查看更多
登录 后发表回答