做一个学生班级的程序,每次运行第二个功能“add a student to a class”都会报错,nullpointer,我知道是因为我在红字的部分创建对象数据。请问要怎么样才能在第一个功能里能够输出4个属性的同时,在第二个功能里也能使用和打印出第一个功能创建过的对象的属性。
public static void main(String[] args) {
String id;
String name;
String age;
String state = null;
int scount=0;
student[] studentlist = new student[100];
System.out.println("What do you want?");
System.out.println("1. Create a student");
System.out.println("2. Add a student to a class");
int menuoption=reader.nextInt();
while (1>0)
{
if (menuoption ==1)
{
System.out.println("id");
id = reader.next();
System.out.println("name");
name = reader.next();
System.out.println("age");
age = reader.next();
System.out.println("state");
state=reader.next();
studentlist[scount] = new student(id, name, age, state);
System.out.print("you have create student with ");
System.out.println(studentlist[count].getid());
System.out.println(studentlist[count].getname());
System.out.println(studentlist[count].getage());
System.out.println(studentlist[count].getstate());
scount=scount+1;
}
if (menuoption==2)
{
System.out.println("you have the following students");
int count;
for (count=0;count<scount)
{
System.out.println(studentlist[count].getid());
System.out.println(studentlist[count].getname());
System.out.println(studentlist[count].getage());
System.out.println(studentlist[count].getstate());
}
}
}
public static void main(String[] args) {
String id;
String name;
String age;
String state = null;
int scount=0;
student[] studentlist = new student[100];
System.out.println("What do you want?");
System.out.println("1. Create a student");
System.out.println("2. Add a student to a class");
int menuoption=reader.nextInt();
while (1>0)
{
if (menuoption ==1)
{
System.out.println("id");
id = reader.next();
System.out.println("name");
name = reader.next();
System.out.println("age");
age = reader.next();
System.out.println("state");
state=reader.next();
studentlist[scount] = new student(id, name, age, state);
System.out.print("you have create student with ");
System.out.println(studentlist[count].getid());
System.out.println(studentlist[count].getname());
System.out.println(studentlist[count].getage());
System.out.println(studentlist[count].getstate());
scount=scount+1;
}
if (menuoption==2)
{
System.out.println("you have the following students");
int count;
for (count=0;count<scount)
{
System.out.println(studentlist[count].getid());
System.out.println(studentlist[count].getname());
System.out.println(studentlist[count].getage());
System.out.println(studentlist[count].getstate());
}
}
}
case 1:
System.out.println("id");
...
case 2:
System.out.println("you have the following students");
...
break;
}
还有能讲一下原理吗,为什么if不行,switch就行
if (menuoption==1) {
System.out.println("id");
...
}
if (menuoption<=2) {
System.out.println("you have the following students");
...
}此外,如果代码太长,应该将其另外封装为函数。