[英]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)
尝试捕获引发的异常类型,而不是NumberFormatException
( InputMismatchException
)。
消息很清楚: 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.