I am working on a recipe manager project in Java where I have the user input: name of the ingredient, calories per cup of the ingredient, cups of the ingredient, and finally the program will then calculate the total of calories total.
My issue is that if a user inputs a letter or symbol, then the program crashes. I would like to know how I can fix that. Any help would be great!
Here is my code:
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.");
}
}
Thanks, everyone!