【发布时间】:2021-04-25 02:10:04
【问题描述】:
我正在尝试编写一种方法来从文件中读取数组列表,然后将其显示在屏幕上,但最终无法正常工作。这是我正在使用的方法:
说明:
- Point 类包含构造函数、getter、setter、toString()
- PrintPoint 类包含构造函数、打印方法和从文件读取方法
- 要测试的TestPoint 类
点类
public class Point {
private double x;
private double y;
private String name;
public Point(String name, double x, double y){
this.name = name;
this.x = x;
this.y = y;
}
//setter and getter
@Override
public String toString(){
return this.name + "[" + this.x + ", " + this.y + "]";
}
}
PrintPoint 类
import java.util.*;
import java.io.*;
public class PrintPoint {
private ArrayList<Point> pointList;
//Constructor
public PrintPoint(String path) throws FileNotFoundException{
pointList = getPointFromFile(path);
}
//Print method
public void printPointList(){
for(Point p : pointList){
System.out.println(p);
}
}
//Read from file method
public ArrayList<Point> getPointFromFile(String path) throws FileNotFoundException{
try {
Scanner myReader = new Scanner(new File(path));
ArrayList<String> list = new ArrayList<String>();
while (myReader.hasNextLine()) {
list.add(myReader.nextLine());
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return new ArrayList<Point>();
}
}
TestPoint 类:
import java.util.*;
import java.io.*;
public class TestPoint {
public static void main(String[] args) throws FileNotFoundException{
PrintPoint a = new PrintPoint("arraylist.txt");
a.printPointList();
}
}
arraylist.txt
A,3,4
B,5,6
C,7,8
我想打印数组列表但它不起作用(没有错误只是不打印)。
已更新:我已将问题更新为另一个要求。
【问题讨论】:
-
您从 getPointFromFile() 方法返回一个空的 ArrayList
-
您是否使用 Eclipse 来自动完成您的功能?因为如果您忘记了
return,Eclipse 会准确地建议您这样做。我建议不要一开始就过度依赖你的 IDE,因为基于对代码的有限理解,它通常会给出糟糕的建议,尤其是在类型系统传达很少信息的 Java 等语言中。