gpt4 book ai didi

java - java空异常

转载 作者:行者123 更新时间:2023-12-01 17:30:25 25 4
gpt4 key购买 nike

我收到一个错误,提示 java.lang.NullPointerException: null每当我运行代码时就从代码中获取。

这是代码:

public class APRectangle
{
private APPoint myTopLeft;
private APPoint myTopRight;
private APPoint myBottomLeft;
private APPoint myBottomRight;
private double myWidth;
private double myHeight;

public APRectangle( APPoint topLeft, double width, double height )
{
myTopLeft = topLeft;
myWidth = width;
myHeight = height;
}

public APPoint getTopLeft()
{
return myTopLeft;
}

public void setTopLeft( APPoint TL )
{
myTopLeft = TL;
}

public double getWidth()
{
return myWidth;
}

public void setWidth( double W )
{
myWidth = W;
}

public double getHeight()
{
return myHeight;
}

public void setHeight( double H )
{
myHeight = H;
}

public APPoint getTopRight()
{
return new APPoint( myTopLeft.getX() + myWidth, myTopLeft.getY() );
}

public APPoint getBottomLeft()
{
return new APPoint( myTopLeft.getX(), myTopLeft.getY() - myHeight );
}

public APPoint getBottomRight()
{
return new APPoint( myTopRight.getX(), myTopRight.getY() - myHeight );
}
}

最后一种方法是给我错误的方法。

这是我的主要类(class):

public class MainClass
{
public MainClass()
{
}

public static String printAPPoint( APPoint p )
{
return "(" + p.getX() + "," + p.getY() + ")";
}

public static String printAPRectangle( APRectangle R)
{
return "[APRectangle " + printAPPoint(R.getTopLeft()) +
" " + R.getWidth() + "," + R.getHeight() + "]" ;
}

public static String printTopLeft( APRectangle R )
{
return "(Top Left is " + printAPPoint(R.getTopLeft()) + ")" ;
}

public static String printTopRight( APRectangle R )
{
return "(Top Right is " + printAPPoint(R.getTopRight()) + ")" ;
}

public static String printBottomLeft( APRectangle R )
{
return "(Bottom Left is " + printAPPoint(R.getBottomLeft()) + ")";
}

public static String printBottomRight( APRectangle R )
{
return "(Bottom Right is " + printAPPoint(R.getBottomRight()) + ")";
}

public static void main(String[] args)
{
APPoint p = new APPoint(1.0, 5.0 );
APRectangle R = new APRectangle( p, 5.0, 3.0);
System.out.println(printAPRectangle(R));
System.out.println(printTopLeft(R));
System.out.println(printTopRight(R));
System.out.println(printBottomLeft(R));
System.out.println(printBottomRight(R));
System.out.println( "Done!" );
}

}

最后一种方法之前的三种方法都工作得很好,但我不知道为什么最后一种方法不起作用。有人能帮助我吗?

谢谢,罗汉

最佳答案

您忘记初始化myTopRightmyBottomLeftmyBottomRight。其他方法工作得很好,因为您没有使用它们的实际点(但您可能应该使用)。 AP 计算机科学?

顺便说一句,您的异常消息是这样说的:我们遇到了问题,因为我们的对象之一不存在。我们在尝试 APRectangle.getBottomRight(第 59 行)时发现了问题。我们正在执行 APRectangle.getBottomRight,因为 MainClass.printBottomRight(第 35 行)告诉我们这样做。我们正在执行 MainClass.printBottomRight,因为 MainClass.main(第 46 行)告诉我们这样做。希望这能解决问题。

关于java - java空异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11606017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com