I want my code to print out the recipe object that contains the name that the user inputs in the terminal.
I get the error in the title down in the line "for(Recipe x : list)". I don’t understand why this occurs because the list is initialized as a Recipe ArrayList and I am going through the loop with a Recipe object. Any help is appreciated.
public class RecipeSearch {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList list = new ArrayList<Recipe>();
System.out.println("File to read:");
String file = scanner.nextLine();
try(Scanner reader = new Scanner(Paths.get(file))){
while(reader.hasNextLine()){
String name = reader.nextLine();
int time = Integer.valueOf(reader.nextLine());
Recipe recipe = new Recipe(name, time);
list.add(recipe);
while(reader.hasNextLine()){
String ingredient = reader.nextLine();
if(ingredient.isEmpty()){
break;
}
recipe.addIngredient(ingredient);
}
}
} catch(Exception e){
System.out.println("Error");
}
System.out.println("Commands:");
System.out.println("find name - searches recipe by name");
while(true){
String input = scanner.nextLine();
if(input.equals("find name")){
System.out.println("Searched word:");
String name = scanner.nextLine();
for(Recipe x : list){
//THIS LOOP WON'T COMPILE
}
}
}
}
}
public class Recipe {
private String name;
private int time;
private ArrayList<String> ingredients;
public Recipe(String name, int time){
this.name = name;
this.time = time;
this.ingredients = new ArrayList<>();
}
public String getName(){
return this.name;
}
public int getTime(){
return this.time;
}
public ArrayList<String> getIngredients(){
return this.ingredients;
}
public void addIngredient(String ingredient){
this.ingredients.add(ingredient);
}
@Override
public String toString(){
return this.name + ", cooking time: " + this.time;
}
}
>Solution :
The problem is here:
ArrayList list = new ArrayList<Recipe>();
You need specific the datatype in the declaration of the list (or cast it in the for)
You should write it like this:
List<Recipe> list = new ArrayList<Recipe>();
It doesn’t have to be List, but it’s good practice to use the parent interface