Java NullPointerException的问题

Java NullPointerException的问题,java,nullpointerexception,Java,Nullpointerexception,今天我有一个评估问题,我必须创建两个类:Dress和TestClass。 我完成了这些类,但当我试图运行该程序时,收到一条NullPointerException消息。以下是我的课程: 班级服装: public class Dress { String colors []; int sizes []; public Dress ( String colors [], int sizes []){ this.colors = new String [col

今天我有一个评估问题,我必须创建两个类:Dress和TestClass。 我完成了这些类,但当我试图运行该程序时,收到一条NullPointerException消息。以下是我的课程:

班级服装:

public class Dress {
    String colors []; 
    int sizes [];

    public Dress ( String colors [], int sizes []){
       this.colors = new String [colors.length];
       this.sizes = new int [sizes.length] ;
       this.colors = colors;
       this.sizes = sizes;
    }

    public boolean search (String color){
       for (int i =0; i<colors.length;i++)
           if (colors [i].equals(color))
              return true;
       return false;
    }
    public boolean search (int size){
       for (int i =0; i<sizes.length;i++)
           if (sizes [i] == size)
              return true;
       return false;
    }
}
public class Tests {
    public static void main (String args []){
       String color[] = {"Pink","Blue","Red"};
       int size[] = {8,9,7};
       Dress d = new Dress (color, size);
       System.out.println(d.search("Pink"));
       System.out.println(d.search(8));
    }
}

仅供参考-将可变引用分配给私有数据成员不是一个好主意:

this.colors = new String [colors.length];  // The new reference is discarded after reassignment on next line
this.colors = colors;  // The program that passes this reference can modify it; changes will be visible to your class instance.
任何获得该引用并更改其状态的人都将更改您的实例数据成员,而不考虑其私有状态

以下是正确的方法(为了清晰起见,只有一种):


您应该始终制作私有、可变数据的防御性副本。

如果您询问收到的错误,请提供错误消息(在您的情况下,请提供异常和堆栈跟踪),以便我们可以帮助您了解如何调试NPE。该键位于异常堆栈跟踪中,它将告诉您异常的行号。检查该行上的变量,找到空的变量,然后检查代码以了解原因。如果您仍然需要帮助,您必须在这里发布异常stacktrace文本,并告诉我们哪一行抛出异常。请注意,构造函数的前两行是不必要的,并且具有误导性,因此请将它们删除。This
This.colors=新字符串[colors.length]
this.size=新的int[size.length]可以删除。顺便说一下,您的代码可以正常工作。为了可读性起见,请使用大括号和For循环、if语句以及一致的缩进。您的代码工作正常。请再次检查。结果:真的,你看,问题是,我告诉我的老师前两行没有必要,但她坚持要这么做。她告诉我应该将参数中的值赋给数组,该数组在构造函数方法的第3行和第4行可见。但出于某种原因,它忽略了第3行和第4行,给了我一个空点例外。我不在乎你的老师或你告诉她的。我所介绍的是初始化这些数组的正确方法。这是一种多么好的方式,很明显,您没有读过前两行。我问了一个问题,但现在我已经找到了答案,这无关紧要;只是一个事实陈述。如果代码仍然像你发布的一样,那么它仍然是错误的。总有一天你会发现,并想知道为什么。
public Dress(String [] colors) {
    if (colors == null) throw new IllegalArgumentException("colors cannot be null");
    this.colors = new String[colors.length];
    // Copy the values from the parameter array into the new, private array.
    System.arraycopy(colors, 0, this.colors, 0, this.colors.length);
}