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)
尝试捕获引发的异常类型,而不是NumberFormatException
( InputMismatchException
)。
The message is pretty clear: Scanner.nextInt()
throws an InputMismatchException
, but your code catches NumberFormatException
. Catch the appropriate exception type.
While using Scanner.nextInt()
, it causes some problems. When you use Scanner.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 a Scanner.nextLine()
. You can discard the result.
It's for this reason that I suggest always using nextLine
(or BufferedReader.readLine()
) and doing the parsing after using Integer.parseInt()
. Your code should be as follows.
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");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.