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
第一行中的第一个数字表示文本文件中的点数。 读取文件时出错。我想得到的输出是{(2.0,7.0),(3.0,5.0),(11.0,17.0),(23.0,19.0),(150.0,1.0)}。我该如何解决?
答案 0 :(得分:2)
向toString
添加Point
方法,将Point
格式化为x, y
public class Point {
//...
@Override
public String toString() {
return x + ", " + y;
}
}
移动toString
方法,使其在PointArray
中定义,您也可以考虑使用StringJoiner
让您的生活更简单
public class PointArray {
//...
@Override
public String toString() {
StringJoiner sj = new StringJoiner(", ", "{", "}");
for (int i = 0; i < points.length; i++) {
sj.add("(" + points[i].toString() + ")");
}
return sj.toString();
}
}