【发布时间】:2014-09-14 02:29:37
【问题描述】:
在这个类中,我定义了一个构造函数,它初始化一个数组并用 Point2D.Double 填充它。我想定义一个在数组中输出 Point2D.Double 的 toString 方法。所以在 toString 方法中,我创建了一个 for 循环,返回数组中的每个 Point2D.Double。问题是,我不知道为什么 Eclipse 告诉我 for 语句中的更新是死代码。
import java.awt.geom.Point2D;
public class SimplePolygon {
public int n; // number of vertices of the polygon
public Point2D.Double[] vertices; // vertices[0..n-1] around the polygon
// boundary
public SimplePolygon(int size) {
n = size;
vertices = new Point2D.Double[n]; // creates array with n size. Elements are doubles.
for(int i = 0; i < n; i++)
{
Point2D.Double point = new Point2D.Double(Math.random() * 6, Math.random() * 6);
vertices[i] = point;
}
}
public String toString() {
for(int i = 0 ; i < n ; i++)
{
return "" + vertices[i];
}
return "";
}
【问题讨论】:
-
See.
-
更改你的 toString(): 1) 创建一个新变量
String s = "";2) 将 'return "" + vertices[i]' 更改为s += vertices[i];, 3) 循环完成后, @987654325 @