根据以下要求帮我修改上述代码:Add to the Model class a new method called savaData that saves into a text file called "points.txt" the integer coordinates x and y of each point in the arraylist of points. Also modify the constructor of the Model class to read the integer coordinates of all the points from the same text file, if it exists, and put them into the arraylist of points (if the file does not exist then the arraylist of points should remain empty).
时间: 2023-12-30 22:02:33 浏览: 69
好的,我可以帮您修改代码。请看下面的代码:
```
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Model {
private ArrayList<Point> points;
public Model() {
points = new ArrayList<Point>();
try {
BufferedReader reader = new BufferedReader(new FileReader("points.txt"));
String line = reader.readLine();
while (line != null) {
String[] coords = line.split(",");
int x = Integer.parseInt(coords[0]);
int y = Integer.parseInt(coords[1]);
Point p = new Point(x, y);
points.add(p);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
// Do nothing if the file does not exist
}
}
public void addPoint(Point p) {
points.add(p);
}
public ArrayList<Point> getPoints() {
return points;
}
public void saveData() {
try {
PrintWriter writer = new PrintWriter("points.txt", "UTF-8");
for (Point p : points) {
writer.println(p.getX() + "," + p.getY());
}
writer.close();
} catch (IOException e) {
System.out.println("Error saving data to file.");
}
}
}
```
我添加了一个名为 `saveData()` 的新方法,它将点坐标写入名为 "points.txt" 的文件中。我还修改了构造函数,以从该文件中读取所有点的坐标,并将它们放入点列表中(如果文件不存在,则点列表应该保持为空)。
阅读全文