【问题标题】:how to return a Point in this example在这个例子中如何返回一个点
【发布时间】:2013-10-09 02:09:35
【问题描述】:

我正在尝试从一个扩展 shape 类的 circle.java 类返回一个 Point。我现在不断收到空指针异常。我需要使用继承的 getPoints() 重新运行中心点;方法,但是 inhereted 方法返回一个数组,并且要从 circle 返回的值不是一个数组。如果不使用单独的返回方法,我将如何返回中心点。 我的 Shape 类如下

import java.awt.Point;

public abstract class Shape {
private String  name;
private Point[] points;
protected Shape(){};
protected Shape(String aName) {
    name = aName;
}

public final String getName() {
    // TODO Implement method
    return name;
}

protected final void setPoints(Point[] thePoints) {
    points = thePoints;
}

public final Point[] getPoints() {
    // TODO Implement method
    return points;
}

public abstract double getPerimeter();

public static double getDistance(Point one, Point two) {
    double x = one.getX();
    double y = one.getY();
    double x2 = two.getX();
    double y2 = two.getY();
    double x3 = x - x2;
    double y3 = y - y2;
    double ypow = Math.pow(y3, 2);
    double xpow = Math.pow(x3, 2);
    double added = xpow + ypow;
    double distance = Math.sqrt(added);
    return distance;
}
}

我的圈子班是追随者

import java.awt.Point;

public class Circle extends Shape{

private double radius;

public Circle(Point center, int aradius) {
super("Circle");

radius = aradius;
if(radius < 0){
    radius = 0;
}
else{
radius = aradius;
}

}

@Override
public double getPerimeter() {
double perim = 2 * Math.PI * radius;
return perim;
}
  public double getRadius(){
  return radius;
}

}

【问题讨论】:

  • 我们可以看到异常跟踪
  • 值得注意的是,Circle(Point, int) 构造函数中名为 centerPoint 并未在任何地方使用。不确定这是否与您的问题有关。

标签: java inheritance methods nullpointerexception


【解决方案1】:

我能想到的最简单的解决方案就是使用Shape 类中的setPoints 方法...

public Circle(Point center, int aradius) {
    super("Circle");
    //...
    setPoints(new Point[]{center});
}

【讨论】:

    【解决方案2】:

    您获得NullPointerException 的原因是因为您从来没有setPointsShape

    我不确定points 应该包含什么,但对我来说唯一有意义的是形状内的所有点。哪个 IMO 用圆形等形状来确定有点棘手,而确定中心点似乎更棘手(尽管我猜对于圆形来说,根据顺序,它几乎是数组的中间点?)。

    (重新考虑points 还可以包含子类决定的任何内容,例如圆的 1 个中心点和矩形的 4 个点..)

    无论如何,您必须先用一些数据填充Shapepoints 数组(通过调用setPoints),然后才能使用getPoints

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2016-03-20
      • 2019-01-12
      • 1970-01-01
      • 2019-11-07
      • 2020-05-18
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      相关资源
      最近更新 更多