gpt4 book ai didi

java - 插入二维字符串数组时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 08:09:57 25 4
gpt4 key购买 nike

我有一个名为 input1.txt 的文件,其内容如下:

a b c d

bd

c d

d e

我想读取它并将它们放入二维字符串数组中。我已经为它编写了代码。但它显示空指针异常。错误可能出在哪里?下面是我的代码:

我在 graphNodes[i][j] = s; 行中收到异常

BufferedReader br = null;
BufferedReader cr = null;
int lines = 0;
try {
br = new BufferedReader(new FileReader(filename));
try {
while (br.readLine() != null) {
lines++;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
List<String> nodes = new ArrayList<String>();
String[][] graphNodes = new String[lines][];
String[] line = new String[lines];
int i = 0;
int j = 0, x = 0;
try {
cr = new BufferedReader(new FileReader(filename));
while (cr.readLine() != null) {
line[x] = cr.readLine();
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
i++;
x++;
}
} catch (IOException e) {
e.printStackTrace();
}

最佳答案

graphNodes 缺少列长度

String[][] graphNodes = new String[lines][];

在你的问题中,一旦你得到字母,你就可以初始化二维数组的列

String[] letters = line[x].split(" ");
graphNodes[i] = new String[letters.length];

关于java - 插入二维字符串数组时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18296908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com