Java 实例化的对象在包含对象的数组列表中显示为null
我对Java非常陌生,但遇到了以下错误:线程“main”Java.lang.NullPointerException中的异常:无法调用“bussines.Plot$Rectangle.setRectangle(int,int)”,因为“Java.util.ArrayList.get(int).Rectangle”在bussines.Owner.buyRectangle(Owner.Java:24)在construction.Application.run(Application.Java:17)中为nullat construction.Application.main(Application.java:36) 我将在下面插入相关代码段:Java 实例化的对象在包含对象的数组列表中显示为null,java,arraylist,Java,Arraylist,我对Java非常陌生,但遇到了以下错误:线程“main”Java.lang.NullPointerException中的异常:无法调用“bussines.Plot$Rectangle.setRectangle(int,int)”,因为“Java.util.ArrayList.get(int).Rectangle”在bussines.Owner.buyRectangle(Owner.Java:24)在construction.Application.run(Application.Java:17)
public class Plot
{
Rectangle rectangle;
Square square;
public class Rectangle
{
public int length;
public int width;
}
public Rectangle()
{
length = 0;
width = 0;
}
public void setRectangle(int l, int w)
{
length = l;
width = w;
}
public int getArea()
{
return length * width;
}
}
public class Square
{
public int size;
public Square()
{
size = 0;
}
public void setSquare(int s)
{
size = s;
}
public int getArea()
{
return size * size;
}
}
}
调整绘图类。您需要在构造函数中初始化矩形和正方形对象
landPlots.get(0).rectangle.setRectangle(l, w);
否则,由于矩形类为null,您的行将有一个null异常
Buying four plots.
Exception in thread "main" java.lang.NullPointerException
at Owner.buyRectangle(Owner.java:24)
at Application.run(Application.java:16)
at NullExceptionApplication.main(NullExceptionApplication.java:6)
Process finished with exit code 1
我做了测试,现在可以了
public class Plot {
Rectangle rectangle;
Square square;
public Plot() {
rectangle = new Rectangle();
square = new Square();
}
public class Rectangle {
public int length;
public int width;
public Rectangle() {
this.length = 0;
this.width = 0;
}
public void setRectangle(int l, int w) {
length = l;
width = w;
}
public int getArea() {
return length * width;
}
}
public class Square {
public int size;
public Square() {
size = 0;
}
public void setSquare(int s) {
size = s;
}
public int getArea() {
return size * size;
}
}
}
不是arraylist中的对象本身为空,而是
绘图
对象中的矩形
和正方形
字段为空。这里的异常stacktrace保存了关于错误的所有必要信息。谢谢@maloomeister,但我似乎找不到解决方法。。。
Buying four plots.
Exception in thread "main" java.lang.NullPointerException
at Owner.buyRectangle(Owner.java:24)
at Application.run(Application.java:16)
at NullExceptionApplication.main(NullExceptionApplication.java:6)
Process finished with exit code 1
public class Plot {
Rectangle rectangle;
Square square;
public Plot() {
rectangle = new Rectangle();
square = new Square();
}
public class Rectangle {
public int length;
public int width;
public Rectangle() {
this.length = 0;
this.width = 0;
}
public void setRectangle(int l, int w) {
length = l;
width = w;
}
public int getArea() {
return length * width;
}
}
public class Square {
public int size;
public Square() {
size = 0;
}
public void setSquare(int s) {
size = s;
}
public int getArea() {
return size * size;
}
}
}