【发布时间】:2016-04-08 03:17:46
【问题描述】:
我一直在寻找如何解决这个问题,但我找不到适用/适用于我的问题的东西。我正在尝试打印出Circles 的数组。我只知道我必须覆盖toString() 方法。
我不断得到以下输出:
[Heather$Circle@2a139a55, Heather$Circle@15db9742, Heather$Circle@6d06d69c, Heather$Circle@7852e922]
import java.util.*;
public class heather {
public static void main(String[] args) {
heather c = new heather();
Circle c1 = c.new Circle(4,6,4);
Circle c2 = c.new Circle(4,5,4);
Circle c3 = c.new Circle(5,4,4);
Circle c4 = c.new Circle(5,4,3);
Circle[] a = {c1, c2, c3, c4};
Arrays.sort(a);
System.out.print(Arrays.toString(a));
}
public class Point {
private int x;
private int y;
public Point(int x, int y){
this.x = x; this.y = y;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
}
public class Circle extends Point implements Comparable<Circle> {
private double radius;
private Point point;
public Circle(int x, int y, double radius) {
super(x, y); this.radius = radius;
}
public double getRadius() {
return this.radius;
}
public Point getPoint() {
return this.point;
}
public int area() {
return (int) (Math.PI*radius*radius);
}
public int compareTo(Circle other){
if(this.area()>other.area()) {
return 1;
}
if(this.area()<other.area()) {
return -1;
} else if(this.getX()>other.getX()) {
return 1;
}
if (this.getX()<other.getX()){
return -1;
} else if(this.getY()<other.getY()) {
return -1;
} else {
return 1;
}
}
}
public String toString(){
}
}
【问题讨论】:
-
需要填写
toString方法 -
我知道它需要填写。但是,我不知道在里面放什么。我已经尝试过使用 getter 方法和其他东西,但我总是得到红色下划线。
-
嗯,也许吧....
return "Radius: "+radius+" || X: "super.getX()+" || Y: "+super.getY();这真的完全取决于你想要它打印出来的内容。 -
@3kings:我得到了红色下划线,说明我应该为半径创建一个局部变量,并且“getX()”对于类型对象是未定义的
-
嗯......你不应该......你声明了一个名为
radius的变量,并且在你的自定义点类中你有getX()和getY()也许试试?return "Radius: "+getRadius()+" || X: "getPoint().getX()+" || Y: "+getPoint().getY();