In: Computer Science
My Java program keeps "running." I know I need to close a "loop" but I can't find it. I'm learning how to code. This is confusing for me.
import java.util.Scanner;
import java.util.ArrayList;
public class SteppingStone4_Loops {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String recipeName = "";
ArrayList<String> ingredientList = new ArrayList();
String newIngredient = "";
boolean addMoreIngredients = true;
System.out.println("Please enter the recipe name: ");
recipeName = scnr.nextLine();
do {
System.out.println("Would you like to enter an ingredient: (y or
n)");
String reply = scnr.next().toLowerCase();
if (reply.equals("y")) {
System.out.println("Enter the name of the ingredient.");
newIngredient = scnr.next();
ingredientList.add(newIngredient);
} else if (!reply.equals("n")) {
System.out.println("Please enter y or n");
} else {
addMoreIngredients = false;
}
} while (addMoreIngredients);
for (int i = 0; i < ingredientList.size(); i++) {
String ingredient = (String) ingredientList.get(i);
System.out.println(ingredient);
}
}
}
Updated Java Program :
import java.util.Scanner;
import java.util.ArrayList;
public class SteppingStone4_Loops {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String recipeName = "";
ArrayList<String> ingredientList = new ArrayList<String>();
String newIngredient = "";
boolean addMoreIngredients = true;
System.out.print("Please enter the recipe name: ");
recipeName = scnr.nextLine();
do {
System.out.print("Would you like to enter an ingredient: (y or n) : ");
String reply = scnr.next().toLowerCase();
if (reply.equals("y")) {
System.out.print("Enter the name of the ingredient. : ");
newIngredient = scnr.next();
ingredientList.add(newIngredient);
} else if (!reply.equals("n")) {
System.out.println("Please enter y or n !!! ");
} else {
addMoreIngredients = false;
}
} while (addMoreIngredients == true);
System.out.println("\n***************************************\n");
System.out.println("Recipe Name : " + recipeName);
for (int i = 0; i < ingredientList.size(); i++) {
String ingredient = (String) ingredientList.get(i);
System.out.println("Ingredient " + (i+1) + " : " + ingredient);
}
System.out.println("\n***************************************");
}
}
Output:
Thumbs Up Please !!!