数组搜索的IndexOutOfBoundsException

时间:2013-08-07 16:05:18

标签: java replace indexoutofboundsexception

此代码旨在使用另一列array的2列在array.中执行搜索和替换。此时此行返回IndexOutOfBoundsException

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

我是Java新手,所以我不太了解这种语法如何解决问题。整个搜索和替换代码块是:

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

for(int i=0;i<hexLibrary.length;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
}

构建用于执行替换的array的代码是:

String thisLine;  
String[] temp;
String delimiter=",";  
String [][] hexLibrary = new String[501][2];  

try {
    BufferedReader br= new BufferedReader(new FileReader("hexlibrary.txt"));  

    for (int j=0; j<501; j++) {  
        thisLine=br.readLine(); 
        if (thisLine != null) {
            temp = thisLine.split(delimiter);  
            for (int i = 0; i < 2; i++) {  
                hexLibrary[j][i]=temp[i];  
            }  
        } else {
            JOptionPane.showMessageDialog(null,"Library file corrupt.");
            break; // no point in continuing to loop
        }
    }

}

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

以下是初始化“fileContents”array.

的代码
String FileName; // set file variable
FileName = fileName.getText(); // get file name

ArrayList<String> fileContents = new ArrayList<String>(); // create arraylist

BufferedReader reader = new BufferedReader(new FileReader(FileName)); // create reader
String line = null;

while ((line = reader.readLine()) != null) {
    if(line.length() > 0){       // don't include blank lines
        line = line.trim();      // remove whitespaces
        fileContents.add(line);  // add to array
    }
}

1 个答案:

答案 0 :(得分:2)

我们需要查看fileContents是什么,但如果没有看到,请考虑您的代码:

for(int i=0;i<hexLibrary.length;i++) {  
    fileContents.set(i, fileContents.get(i).replace(hexLibrary[i][0], hexLibrary[i][1]));
}

你将i从0迭代到hexLibrary.length-1,但你也使用i作为fileContents.get(i)的索引。如果fileContents的长度小于hexLibrary的长度,那么你将在fileContents.get(i)上得到一个OOB错误。

再次,只是猜测,但似乎你想要做的是通过fileContents中的每一行然后遍历hexLibrary中的每一行为该行,在这种情况下,这正是你应该做的做(你的代码不这样做):

for (int k = 0; k < fileContents.size(); ++ k) {
    for(int i=0;i<hexLibrary.length;i++) {  
        fileContents.set(k, fileContents.get(k).replace(hexLibrary[i][0], hexLibrary[i][1]));
    }
}

我可能错了你想要做的事。