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());
}
}
我正在尝试将值传递给数组对象stemp,它具有两个属性name和age。将值输入到数组的正确语法是什么?上面的语法是否正确?
答案 0 :(得分:1)
您需要添加stemp[j] = new staples();
,否则您将获得NPE。
在Java中创建数组时,JVM会为对象分配N
引用的空间,但不会为对象本身分配空间。您需要使用new
运算符逐个分配这些。
for ( j=0;j<8;j++)
{
stemp[j] = new staples();
System.out.print("Enter your name : ");
stemp[j].setName(reader.readLine());
System.out.println("Enter your age : ");
stemp[j].setAge(Integer.parseInt(reader.readLine()));
}
答案 1 :(得分:0)
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] = new staples();
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());
}
}