import java.io.*;
public class Point
{
private double x;
private double y;
public Point(double x_coord, double y_coord)
{
x = x_coord;
y = y_coord;
}
}
public class PointArray
{
private Point points[];
public PointArray ( FileInputStream fileIn) throws IOException
{
try
{
BufferedReader inputStream = new BufferedReader( new InputStreamReader(fileIn));
int numberOfPoints = Integer.parseInt(inputStream.readLine());
points = new Point[numberOfPoints];
int i=0;
String line;
while ((line = inputStream.readLine()) != null)
{
System.out.print(line);
double x = Double.parseDouble(line.split(" ")[0]);
double y = Double.parseDouble(line.split(" ")[1]);
points[i] = new Point (x, y);
i++;
}
inputStream.close();
}
catch (IOException e)
{
System.out.println("Error");
System.exit(0);
}
}
}
public String toString()
{
String format = "{";
for (int i = 0; i < points.length; i++)
{
if (i < points.length-1)
format = format + points[i] + ", ";
else
format = format + points[i];
}
format = format + "}";
return format;
}
public static void main(String[]args)
{
FileInputStream five = new FileInputStream(new File("fivePoints.txt"));
PointArray fivePoints = new PointArray (five);
System.out.println(fivePoints.toString());
}
txt文件fivePoints如下所示:
5
2 7
3 5
11 17
23 19
150 1
第一行中的数字是点数。
我的问题: 当我编译程序时,一切都很好。但是,当我调用main方法时,我只能打印出来像2 73 511 1723 19150 1 4000 30000.我想通过使用toString()将5个不同的点转换为坐标形式。我该如何解决?
答案 0 :(得分:0)
如果我理解了您的要求,您需要对代码进行一些修改才能打印如下所示的点:
{(2.0, 7.0)(3.0, 5.0)(11.0, 17.0)(23.0, 19.0)(150.0, 1.0)}
要通过调用toString()
来实现上述输出,您需要执行以下操作:
1)覆盖toString()
类中的Point
方法,如下所示(这是您设置单个Point对象的位置):
public String toString() {
return "(" + x + ", " + y + ")";
}
2)您需要修改overrided toString()
类中的PointArray
方法,如下所示(这是您格式化的Point对象数组的位置):
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
for(int i = 0; i < points.length; i++) {
sb.append(points[i].toString());
}
sb.append("}");
return sb.toString();
}
如果有以上两个,您应该能够获得上面显示的输出。
正如@MadProgrammer评论的那样,从while循环的开头删除System.out.print(line);
,因为它会让你感到困惑。