我有一个名为input1.txt的文件,其内容如下:
a、b、c、d
B d
C-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();
}发布于 2013-08-18 08:09:17
我相信您对以下代码有问题:
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++;
}
}这个while语句说“wasn cr.readLine() != null”,此时它读取文件的第一行,并将其与null进行比较,并且它不是null,因此它进入循环。然后让它将linex设置为cr.readLine(),然后读取文件的下一行,并将其设置为linex。因此,跳过第一行代码,只会使用它检查while循环条件。
我想你在自己的循环中想要的是这样
try {
cr = new BufferedReader(new FileReader(filename));
for(String lineValue = cr.readLine(); lineValue != null; x++, lineValue = cr.readLine()) {
line[x] = lineValue;
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++;
}
} 但是,正如前面有人提到的,您需要声明二维数组的大小。为了这个循环,我刚刚把它变成了String[lines][100],但是您需要调整它以满足您的需要(不管您预计最长的字母行有多长)。
发布于 2013-08-18 08:17:46
首先,您没有为第二个维度指定一个值:String[][] graphnodes = new String[lines][]。这意味着您基本上是在尝试将s设置为不存在的值。您可以尝试先定义String[] letters,然后执行类似于String[][] graphnodes = new String[lines][letters.getLength()];的操作。
另外,while (cr.readLine() != null)应该是while (cr.hasNextLine())
如果您执行这样的操作,您的代码也会看起来更简洁:
for (int i = 0, j = 0, x = 0; cr.hasNextLine(); i++, x++) {
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++;
}
}发布于 2013-08-18 08:01:26
首先,你不需要读两遍这些文件。一次获取行数,另一次获得实际数据。您需要阅读这些行,并将它们直接放在列表中。那你就可以用那张单子做你想做的任何事。
https://stackoverflow.com/questions/18296908
复制相似问题