我正在尝试编写一个自动售货机程序,除了告诉它如何处理用户输入字母而不是数字之外,它还做得很好。这是我试图弄清楚的代码块:
System.out.print("Please enter how much money you have to spend (enter -1 to shut down): ");
double custMoney = scanner.nextDouble();
if (custMoney <= 0) {
System.out.println("Thank you for your business!");
System.exit(0);
}
如果用户输入字母而不是数字,它会给我
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at VendingMachine1.main(VendingMachine1.java:28)
如何解决此问题,以便在他们输入字母时提示他们输入有效的数字?
最佳答案
正如@Max所说,您应该将输入读取为字符串,并在它不是数字时提醒用户,我添加了 while(!numberOk) ,这样如果用户输入字母而不是数字(或无效数字),它会继续询问;)
希望这对您有帮助
String custMoney = scanner.next();
double custMoneyValue;
boolean numberOk=false;
while(!numberOk)
try {
custMoneyValue = Double.parseDouble(custMoney);
if (custMoneyValue <= 0) {
System.out.println("Thank you for your business!");
numberOk=true;
System.exit(0); // would make the while loop condition useless...
}
}catch (NumberFormatException e) {
System.out.println("Please insert a number...");
custMoney = scanner.next();
}
关于java - 如何管理用户输入字母而不是数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664928/