2012-01-01 50 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