我正在使用 Java 开发一个食谱管理器项目,用户输入:成分名称、每杯成分的卡路里、成分的杯数,最后程序将计算卡路里总量。
我的问题是,如果用户输入字母或符号,程序就会崩溃。我想知道如何解决这个问题。任何帮助都会很棒!
这是我的代码:
public static void main(String[] args) {
String nameOfIngredient = "";
float numberCups = 0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
System.out.println("Please enter the number of cups of " + nameOfIngredient + " we'll need: ");
numberCups = scnr.nextFloat();
System.out.println("Please enter the name of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and has " + totalCalories + " calories.");
}
谢谢大家!
最佳答案
虽然您的程序适用于有效输入,但您可以通过检查无效输入(例如预期为数字的非数字)来使其健壮。您的程序崩溃是有原因的:当用户在这一行中输入字符串而不是数字时:
numberCups = scnr.nextFloat();
... 然后 nextFloat()
方法将引发一个异常,准确地说是一个NumberFormatException
。 Java 解释器无法处理这种异常——当这种(有效的)情况出现时,它不知道该怎么做。您可以采取一些措施:
do {
bool validInput = true;
try {
numberCups = scnr.nextFloat();
}
catch(NumberFormatException ex) {
validInput = false;
System.out.println("Please enter a number.");
}
} while(!validInput);
现在,Java 将尝试
执行nextFloat
,如果失败并出现NumberFormatException
,它会执行catch
block 。这使您有机会告诉用户他们的输入是错误的。我将所有内容都放在一个循环中,以便在出现异常时,循环简单地再次运行,直到输入有效数字为止。请注意,如果没有出现异常,则永远不会执行 catch
block 。
在这样的 try
block 中,将可能发生预期错误的代码包装起来是一种很好的做法,以便在不使程序不必要地崩溃的情况下处理这种情况。注意这里有 many types of Exceptions .您应该 catch 您预期可能会发生的事情。
关于java - 用户仅输入数字,而不是 Java 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901297/