簡體   English   中英

Java僅使用Scanner接受用戶的數字

[英]Java accepting only numbers from user with Scanner

我試圖了解如何僅接受來自用戶的數字,並且嘗試使用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)

嘗試捕獲引發的異常類型,而不是NumberFormatExceptionInputMismatchException )。

消息很清楚: Scanner.nextInt()引發InputMismatchException ,但是您的代碼捕獲了NumberFormatException 捕獲適當的異常類型。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM