我创建了一个类,将文本文件读取到整数数组中,我相信我做得正确。然后我想在其中创建一个方法 (getInt();) 来获取数组的第一个索引,然后每次调用它时获取以下索引元素。
我有想法在每次调用它以获取以下索引元素时增加它,但我遇到的主要问题是我无法在 try 语句之外访问我的列表,因此我无法为其创建方法。
任何人都可以建议一段代码或关于如何创建此方法的任何建议吗?
import java.io.*;
import java.util.*;
public class ScannerIntegerList {
public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
BufferedReader input = new BufferedReader(file);
List<Integer> list = new ArrayList<Integer>();
String temp = "";
while ((temp = input.readLine()) != null)
if (!temp.trim().equals("0"))
list.add(new Integer(temp));
input.close();
int i = 0;
System.out.println(list.get(i));
i++;
} catch (IOException ie) {
System.out.println(ie);
}
}
}
另外,作为旁注,我正在使用 eclipse,每当我尝试删除 public static void main( String [] args) 时,它都会告诉我我需要它,任何人都可以解释为什么会发生这种情况以及如何解决它,特别是使用这段代码?
当此类完成后,文件名也将来自命令行,因此我们将不胜感激。
提前非常感谢
最佳答案
如果您想在 try block 之外使用 list
,请在外部声明并初始化它。
此外,请使用 try-with-resources使用可关闭资源时,如下所示:
List<Integer> list = new ArrayList<>();
try (BufferedReader input = new BufferedReader(new FileReader("file.txt"))) {
String temp = "";
while ((temp = input.readLine()) != null) {
if (!temp.trim().equals("0")) {
list.add(new Integer(temp));
}
}
} catch (IOException e) {
e.printStackTrace();
}
// you can use list here, knock yourself out
如果文件名来自命令行,
那么你确实需要 public static void main(String[] args)
方法。
您的程序将接收 args 数组中的命令行参数。
如果文件名是第一个命令行参数,
您可以通过args[0]
使用它。
关于Java - 将文件读入数组并随后使用该数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412669/