Brayent Chougah Brayent Chougah - 2 days ago 5
Java Question

How to use table of setters in java constructor

I created a class called plat and another class called Menu

public class plat{
private int price;
private String name;

public int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


the calss Menu

public class Menu {
Scanner sc = new Scanner(System.in);
private plat[] testcompare;

public Menu() {
testcompare = new plat[5];
testcompare[0].setName("pizza");
testcompare[0].setPrice(500);
}


}


so what i'm trying to do is to set the price and name of plat at the moment when i create a Menu with setters and this is what i'm getting in the console

Exception in thread "main" java.lang.NullPointerException
at Menucompare.Menu.<init>(Menu.java:13)
at Menucompare.Main.main(Main.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Answer

You declared an array of plat.

private plat[] testcompare;

You initialize the array to length 5. It means that the array can hold 5 objects of plat.

testcompare = new plat[5];

But you haven't initialized any of the objects in that array. You need to initialize the objects inside the array to be able to store values in them.

testcompare[0] = new plat();
testcompare[0].setName("pizza");
testcompare[0].setPrice(500);
Comments