日期:2014-05-20  浏览次数:20842 次

求助!空指针异常

public class Course {
public static void main(String[] args) {
if(args.length == 1)new Student(args[0]);
if(args.length == 2)new Student(args[0],args[1]);
if(args.length == 3)new Student(args[0],args[1],args[2]);
}
}

class Student{
String studentNumber ;
Book book;
Book book2;

public Student(String s){
this.studentNumber = s;
System.out.println(s);
}
public Student(String s,String s2){
this.studentNumber = s;
this.book.bookName = s2;
System.out.println( s + "chooses" + s2);
}
public Student(String s,String s1,String s2){
this.studentNumber = s;
this.book.bookName = s1;
this.book2.bookName = s2;
System.out.println(s + "chooses" + s1 +"and" + s2);
}

}

class Book{
String bookName;
}


执行时控制台输入一个字符串可以,但是输入两个三个就会抛出空指针异常,怎么解决呢?
------解决方案--------------------

 public Student(String s,String s2){
        this.studentNumber = s;
        this.book.bookName = s2;    //book没有初始化
        System.out.println( s + "chooses" + s2);
    }
    public Student(String s,String s1,String s2){
        this.studentNumber = s;
        this.book.bookName = s1;      //book没有初始化
        this.book2.bookName = s2;     //book2没有初始化
        System.out.println(s + "chooses" + s1 +"and" + s2);
    }



改成下面试试:


public class Course {
public static void main(String[] args) {
if(args.length == 1)new Student(args[0]);
if(args.length == 2)new Student(args[0],args[1]);
if(args.length == 3)new Student(args[0],args[1],args[2]);
}
}

class Student{
String studentNumber ;
Book book = new Book();
Book book2 = new Book();

public Student(String s){
this.studentNumber = s;
System.out.println(s);
}
public Student(String s,String s2){
this.studentNumber = s;
this.book.bookName = s2;
System.out.println( s + "chooses" + s2);
}
public Student(String s,String s1,String s2){
this.studentNumber = s;
this.book.bookName = s1;
this.book2.bookName = s2;
System.out.println(s + "chooses" + s1 +"and" + s2);
}

}

class Book{
String bookName;
}

------解决方案--------------------

//楼上正解,
   public Student(String s,String s2){
        this.studentNumber = s;
        this.book.bookName = s2;//如果你debug的话,可以看出this.book==null,this.book.bookName当然会报错
        System.out.println( s + "chooses" + s2);
    }