gpt4 book ai didi

java - 从文件构建数组中的 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 14:16:10 24 4
gpt4 key购买 nike

*以下代码根据文本文件中的字符串构建“2D”数组。目前它正在返回一个 NullPointException 错误:

temp = thisLine.split(delimiter); My question is, am I correct in understanding that temp is returning null? If so, why, and how do I add a check for null? I'm rather new to Java, and this is my first attempt at creating a string array of arrays from a file.*

--------编辑--------

以上问题已解决。

对于那些感兴趣的人,下面是返回 IndexOutOfBoundsException 的代码。 具体来说是这一行:

fileContents.set(i, fileContents.get(i).replace(hexLibrary[i][0], hexLibrary[i][1]));

System.out.println("SnR after this");

String[][] hexLibrary; // calls the replaces array from the LibToArray method
hexLibrary = LibToArray();

for(int i=0;i<502;i++){
{
fileContents.set(i, fileContents.get(i).replace(hexLibrary[i][0], hexLibrary[i][1]));
}
}
for (String row : fileContents) {
System.out.println(row); // print array to cmd
}
<小时/>

_____________ _________________

<小时/>
    public static String[][] LibToArray()
{

String thisLine;
String[] temp;
String delimiter=",";
String [][] hexLibrary = new String[502][2];
try
{
BufferedReader br= new BufferedReader(new FileReader("hexlibrary.txt"));
for (int j=0; j<502; j++) {
thisLine=br.readLine();
temp = thisLine.split(delimiter);
for (int i = 0; i < 2; i++) {
hexLibrary[j][i]=temp[i];
}
}
}
catch (IOException ex) { // E.H. for try
JOptionPane.showMessageDialog(null, "File not found. Check name and directory."); // error message
}
return hexLibrary;
}

最佳答案

thisLine 更有可能为 null。如果您在读取 ​​502 行之前用完输入,就会发生这种情况。如果 thisLine 不是 null,则 thisLine.split(delimiter) 将不会返回 null。您应该始终检查 null 行:

for (int j=0; j<502; j++) {  
thisLine=br.readLine();
if (thisLine != null) {
temp = thisLine.split(delimiter);
for (int i = 0; i < 2; i++) {
hexLibrary[j][i]=temp[i];
}
} else {
// report error: premature end of input file
break; // no point in continuing to loop
}
}

就我个人而言,我会编写您的方法来不假设任何特定的文件长度:

public static String[][] LibToArray() {
List<String[]> lines = new ArrayList<>();
String delimiter=",";
try (BufferedReader br= new BufferedReader(new FileReader("hexlibrary.txt"))) {
String line = br.readLine();
while (line != null) {
String[] tmp = line.split(delimiter);
// the next line is dangerous--what if there was only one token?
// should add a check that there were at least 2 elements.
lines.add(new String[] {tmp[0], tmp[1]});
line = br.readLine();
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "File not found. Check name and directory.");
}
String[][] hexLibrary = new String[lines.length][];
lines.toArray(hexLibrary);
return hexLibrary;
}

(上面使用了新的 Java 7 try-with-resources syntax 。如果您使用的是早期的 Java,则应该在方法之前添加一个 finally 子句来关闭 br返回。

关于java - 从文件构建数组中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093000/

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