做一个学生班级的程序,每次运行第二个功能“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());
}
}
}

解决方案 »

  1.   

    if 改成 switch,然后第一个case最后不要写break。switch (menuoption) {
    case 1:
      System.out.println("id"); 
      ...
    case 2:
      System.out.println("you have the following students");
      ...
      break;
    }
      

  2.   

    额,这样啊我去试试看。不知道还有没有别的方法啊,因为实际上我不止两个case,然后每个case又都有很长的代码也会用到对象。上面这个是我自己简化以后的代码。
    还有能讲一下原理吗,为什么if不行,switch就行
      

  3.   

    if也可以,只不过你写的条件是互斥的。switch 则缺省可以顺序执行。
    if (menuoption==1) {
      System.out.println("id");
      ...
    }
    if (menuoption<=2) {
      System.out.println("you have the following students");
      ...
    }此外,如果代码太长,应该将其另外封装为函数。
      

  4.   

    离散匹配强烈建议用switch,匹配项不能离散化再考虑if。switch的速度远比if高,典型的空间换时间。