import java.util.ArrayList;
import java.util.Scanner;
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();
/**The code should check the reply:
* "y" --> prompt for the ingredient and add it to the ingredient list;
* "n" --> break out of the loop;
* anything else --> prompt for a "y" or "n"
*/
while (true) {
if (reply.equals("y")) {
System.out.println("Enter ingredient name: ");
newIngredient = scnr.next();
ingredientList.add(newIngredient);
break;
}
else if (reply.equals("n")) {
System.out.println("Goodbye!");
break;
}
else
break;
}
} while (addMoreIngredients);
for (int i = 0; i < ingredientList.size(); i++) {
String ingredient = ingredientList.get(i);
System.out.println(ingredient);
}
}
}
When ran, the program returns this:
Please enter the recipe name:
Polenta
Would you like to enter an ingredient: (y or n)
y
Enter ingredient name:
Salt
Would you like to enter an ingredient: (y or n)
n
Would you like to enter an ingredient: (y or n)
5
Would you like to enter an ingredient: (y or n)
Why doesn't it break when reply = n? Why does it go back to the "Would you like to enter an ingredient"? Can someone pinpoint my mistake or perhaps suggest a different way? Thanks
Aucun commentaire:
Enregistrer un commentaire