我正在用 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.");
}
}
PIPIONE
偶然的你
相关分类