Skip to content
Advertisement

I am having an issue getting my for loop to print all eements of my array in this program

I cant get my array for ingredients to print in the end where the for loop is, it only prints the first element which is the first ingredient entered.

“””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””””‘

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();

     OuterLoop:  
     
     do {
         System.out.println("Would you like to enter an ingredient? (y or n)");
        String reply = scnr.nextLine().toLowerCase();
         switch (reply) 
            
            case "y" :
                System.out.println("Please Enter Ingredient Name: ");
                ingredientList.add(scnr.nextLine()); 
               //Stores/add's user input in ingredient list array
                break; //Breaks to "Would you like to enter more ingredients
            
            case "yes" :
                System.out.println("Please Enter Ingredient Name: ");
                ingredientList.add(scnr.nextLine()); 
                   
                break; //Breaks to "Would you like to enter more ingredients
            
            case "no":
                break OuterLoop; //Break to end program if n selected 
            
            case "n":
                break OuterLoop; //Break to end program if n selected 
            
            default:
                System.out.println("Invalid entry, please enter Y or N");
                break;  //Breaks to "Would you like to enter more ingredients
        }
        
        
      } while (addMoreIngredients); 
     
    
   

    for (int i = 0; i < ingredientList.size(); i++) {
       
        String ingredient = ingredientList.get(i);
        System.out.println(ingredient);
        break;
    }
}
}

Advertisement

Answer

The break in the for-loop prematurely ends the loop.

for (int i = 0; i < ingredientList.size(); i++) {
    String ingredient = ingredientList.get(i);
    System.out.println(ingredient);
    break;
}

Remove that break and it should iterate over all of the elements in the List. Note that you can simplify the iteration with either a for-each loop…

for (String ingredient : ingredientList) {
  System.out.println(ingredient);
}

.. or using the Stream API ..

ingredientList.stream().forEach(ingredient -> System.out.println(ingredient));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement