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)
The message is pretty clear:
Scanner.nextInt()
throws anInputMismatchException
, but your code catchesNumberFormatException
. Catch the appropriate exception type.While using
Scanner.nextInt()
, it causes some problems. When you useScanner.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 aScanner.nextLine()
. You can discard the result.It's for this reason that I suggest always using
nextLine
(orBufferedReader.readLine()
) and doing the parsing after usingInteger.parseInt()
. Your code should be as follows.Try catching the type of exception thrown rather than
NumberFormatException
(InputMismatchException
).