帮我修改以下代码的问题:public Model() { points = new ArrayList<Point>(); listeners = new ArrayList<ModelListener>(); // Read points from file if it exists File file = new File("points.txt"); if (file.exists()) { try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String[] coordinates = scanner.nextLine().split(","); int x = Integer.parseInt(coordinates[0]); int y = Integer.parseInt(coordinates[1]); points.add(new Point(x, y)); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } },, public void saveData() { try { FileWriter writer = new FileWriter("points.txt"); for (Point p : points) { writer.write(p.x + " " + p.y + "\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } }出现以下问题:Exception in thread "main" java.lang.NumberFormatException: For input string: "119.0"
时间: 2024-01-03 17:03:41 浏览: 28
出现该异常是因为在读取文件时,将字符串转换为整数时出错,因为其中的某个字符串不是整数而是一个浮点数。
您可以使用 `Double.parseDouble()` 方法来解决这个问题,将字符串转换为浮点数,然后再将其转换为整数。
以下是修改后的代码:
```
public Model() {
points = new ArrayList<Point>();
listeners = new ArrayList<ModelListener>();
// Read points from file if it exists
File file = new File("points.txt");
if (file.exists()) {
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String[] coordinates = scanner.nextLine().split(",");
int x = (int) Double.parseDouble(coordinates[0]);
int y = (int) Double.parseDouble(coordinates[1]);
points.add(new Point(x, y));
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public void saveData() {
try {
FileWriter writer = new FileWriter("points.txt");
for (Point p : points) {
writer.write(p.x + "," + p.y + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
```
同时,您还需要对保存数据的方法进行修改,将写入文件的坐标值之间的逗号改为空格,以便在读取文件时能够正确地分割字符串。