2 回答
TA贡献1805条经验 获得超9个赞
尝试这个:
public class num {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
getFile(list);
System.out.println("numbers are: " + list);
}
public static void getFile(ArrayList<Integer> list) {
try {
Scanner read = new Scanner(new File("numbers.txt"));
do {
list.add(read.nextInt());
}while (read.hasNext());
} catch (FileNotFoundException fnf) {
System.out.println("File was not found");
}
}
基本上,您的getFile()方法是 void 类型,因此它不会返回任何内容。因此,您需要在此方法中将列表作为参数传递,然后更改该列表。然后您可以在主方法中查看更改。
TA贡献1776条经验 获得超12个赞
您需要将方法的返回类型更改为 List 并将每个 nextInt 存储在本地 ArrayList 中,并且必须在最后返回本地列表!
public class num {
public static void main(String[] args) {
ArrayList<Integer> list = getFile();
list.forEach(System.out::println);
}
public static List<Integer> getFile() {
List res = new ArrayList<Integer>();
try {
Scanner read = new Scanner(new File("numbers.txt"));
do {
res.add(read.nextInt());
}while (read.hasNext());
} catch (FileNotFoundException fnf) {
System.out.println("File was not found");
}
return res;
}
}
添加回答
举报