【问题标题】:Java accepting only numbers from user with ScannerJava 只接受来自使用扫描仪的用户的数字
【发布时间】:2012-01-01 22:46:13
【问题描述】:

我正在尝试了解如何只接受来自用户的数字,并且我尝试使用 try catch 块来这样做,但我仍然会遇到错误。

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

    }

我试图了解它为什么不起作用。

我通过在控制台中输入 a 对其进行了测试,我会收到一个错误,而不是充满希望的“请输入出价”解决方案。

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)

【问题讨论】:

    标签: java input try-catch java.util.scanner integer


    【解决方案1】:

    尝试捕获抛出的异常类型而不是NumberFormatException (InputMismatchException)。

    【讨论】:

      【解决方案2】:

      消息很清楚:Scanner.nextInt() 抛出 InputMismatchException,但您的代码捕获了 NumberFormatException。捕获适当的异常类型。

      【讨论】:

        【解决方案3】:

        在使用Scanner.nextInt() 时,会导致一些问题。当您使用Scanner.nextInt() 时,它不会使用新行(或其他分隔符)本身,因此返回的下一个标记通常是空字符串。因此,您需要使用Scanner.nextLine() 关注它。您可以丢弃结果。

        正是出于这个原因,我建议始终使用nextLine(或BufferedReader.readLine())并在使用Integer.parseInt() 之后进行解析。您的代码应如下所示。

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

        【讨论】:

        • 谢谢!我会记得使用 nextLine() 和 parseInt()
        猜你喜欢
        • 2022-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        相关资源
        最近更新 更多