Java accepting only numbers from user with Scanner

﹥>﹥吖頭↗ 提交于 2019-12-12 02:29:08

问题


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)

回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/8696094/java-accepting-only-numbers-from-user-with-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!