Reputation: 3
I wrote a class called MenuItem
which includes:
private String name;
private String description;
private double price;
public MenuItem(String name, String description, double price)
{
this.name = name;
this.description = description;
this.price = price;
}
as well as accessor and mutator methods for all the variables, and another class called Menu
which includes the constructor:
public Menu()
{
menu = new MenuItem[50];
}
In my main method, I wrote:
Menu menu = new Menu();
in an attempt to create a Menu
array called menu with 50 MenuItem
objects inside. However I know I did something wrong because when I try to refer to one of the objects in the array i.e.
System.out.print("The name of this item is " + menu[1].getName());
I get a compiling error that points to the menu[1] and says array required, but Menu found.
How do I fix this?
Upvotes: 0
Views: 48
Reputation: 64308
Part of the reason you're confused is because you have 3 different 'menus' inside your program right now. You have Menu
, the class. You have menu, the array, which is inside the any instance of the Menu
class. And finally, you have menu the object, which you created inside your main method.
In your main method, when you do menu[1], you're telling Java "take menu, the object, and try and get the first indice of it". However, since the menu inside main isn't an array, Java will not know what to do and will refuse to compile.
Instead, you want to find menu, the array, inside menu, the object, and get the indice of that:
System.out.print("The name is: " + menu.menu[1].getName());
So, to sum up, you have an instance of the Menu
class called menu which contains an array named menu!
I suppose the main takeaway here is to always make sure to use clear and unambiguous variable names to avoid confusion :)
Upvotes: 2
Reputation: 9522
You have two variables calles menu
. This is ok as they are in separate scopes (one is in the main
, one a member of your class Menu
), but maybe that's where the confusion comes from. In the class Menu
, it is an array, but in your main
method, it is a simple variable. So if you want to print out the second element in the array (which is menu[1]
), you must do that in your Menu
class somewhere. (Or create a getter to access it from the main
method).
Upvotes: 0