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);
}
}
}
走った、プログラムがこれを返します。なぜこのループは最初に戻りますか?
レシピ名を入力してください:
ポレンタ
あなたは成分を入力したいと思います:(yまたはn)
Y
成分の名称を入力します。
塩
あなたは成分を入力したいと思います:(yまたはn)
のn
あなたは成分を入力したいと思います:(Yあるいはn)
あなたは成分を入力したいと思います:ときの応答= N(yまたはn)
なぜそれが壊れていないのですか?なぜそれは "あなたは原料を入れたいですか"に戻るのですか?誰かが私の間違いを突き止めたり、別の方法を提案したりすることはできますか?おかげで
であることを確認してください;' reply.equals( "Y") 'や' reply.equals( "N") 'か'ステートメントを。なぜあなたは彼らの行動が異なっていると思いますか? – shmosel
それを考えると、内側のループは決して実際にはループしません。もしあなたがそれを取り除くならば、代わりに外側のものから壊れてしまうでしょう。 – shmosel