2012-01-01 37 views
0

我想了解如何只接受來自用戶的數字,並且我試圖使用try catch塊來這樣做,但我仍然會遇到錯誤。Java只接受用戶使用掃描器的號碼

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

    } 

我想了解爲什麼它不工作。

我通過輸入到控制檯進行測試,我會收到一個錯誤,而不是有希望的「請輸入出價」解決方案。

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

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

謝謝!我會記得使用nextLine()和parseInt() – Streak324 2012-01-01 23:29:52

2

嘗試捕捉拋出的異常,而不是NumberFormatExceptionInputMismatchException)類型。

2

該消息非常明確:Scanner.nextInt()會拋出一個InputMismatchException,但您的代碼捕獲的是NumberFormatException。捕獲適當的異常類型。

+0

對不起,沒有注意到。 – Streak324 2012-01-01 23:29:20