public static void main(String[] args) {
staples[] stemp = new staples[8];
int j;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (j = 0; j < 8; j++) {
System.out.print("Enter your name : ");
stemp[j].setName(reader.readLine());
System.out.println("Enter your age : ");
stemp[j].setAge(Integer.parseInt(reader.readLine()));
}
for (j = 0; j < 8; j++) {
System.out.print("Employee number:" + "j:" + "name:" + stemp[j].getName() + " Age:" + stemp[j].getAge());
}
reader.close(); // VERY IMPORTANT TO CLOSE
System.out.println("Program ended");
} catch (java.io.IOException ex) {
System.out.println("Error is " + ex.getMessage());
}
}
I am trying to pass values to the the array object stemp which has two attributes name and age. What is the correct syntax to input the values to the array? Is the syntax above correct?
You need to add
stemp[j] = new staples();, otherwise you get NPE.When you create an array in Java, JVM allocates space for
Nreferences to your objects, but not for the objects themselves. You need to allocate these one by one using thenewoperator.