因此我编写了这段代码来读取包含数字的文件,但是当我尝试为数组赋值时出现 NullPointerException 错误。
这是我的代码:
private static int []a;
public static int i = 0;
public static void main(String[] args) {
// Get a random generated array
// I'll read from file, which contains generated list of numbers.
BufferedReader reader = null;
try {
File file = new File("numbers.txt");
reader = new BufferedReader(new FileReader(file));
for(String line = reader.readLine(); line!= null; line = reader.readLine()){
//I get error here
a[i] = Integer.parseInt(line);
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
您忘记了初始化数组,您可以使用它来初始化
private static int []a = new int[100];
使用固定大小的数组时要小心,因为在这种特殊情况下,如果您的文件超过 99 行,您的程序将失败。 while 循环会尝试写出数组边界,它会抛出 IndexOutOfBounds
异常。
- 如果你想使用动态大小的数组,只要你添加一个项目就会自动增长,了解ArrayLists .
The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want.
值得一提的是,通常在读取文件时,最好使用while循环而不是for循环:
while ((line = r.readLine()) != null) {
a[i] = Integer.parseInt(reader.readLine());
i++;
}
这样,当 BufferedReader
到达文件末尾时,循环将退出,因为 r.readLine()
方法将返回 null
.
关于java - 如何避免 Buffer Reader 中的 NullPointErexception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58591539/