【发布时间】:2019-03-12 16:55:19
【问题描述】:
我遇到了一个问题,导致我的整个代码无法正常工作。它的数组索引越界错误,但它与文件数组完美匹配,所以我不确定问题是什么..
public void Menu() {
prompt.welcomeMsg();
prompt.nGramOptionMsg();
String userInput = input.next();
while (userInput.charAt(0) != 's' || userInput.charAt(0) != 'S') {
if (userInput.charAt(0) == 'n' || userInput.charAt(0) == 'N') {
prompt.nGramLengthMsg();
int userIntut = input.nextInt();
nGram = new NGram(userIntut);
prompt.fileUpload();
String userFilePut = input.next();
FileOpener file = new FileOpener(userFilePut);
String[] fileArray = file.openFile();
for (int i = 0; i < fileArray.length; i++) {
String[] splitedFileArray = fileArray[i].split("\\s+");
list.add(splitedFileArray[i]);
}
String[] listToStringArray = (String[]) list.toArray(new String[0]);
String[] nGrams = nGram.arrayToNGram(fileArray);
for (int i = 0; i < nGrams.length; i++) {
Word word;
if (!hashMap.containsKey(nGrams[i])) {
word = new Word(nGrams[i], 1);
hashMap.put(word.getNGram(), word);
} else {
Word tempWord = hashMap.remove(nGrams[i]);
tempWord.increaseAbsoluteFrequency();
hashMap.put(tempWord.getNGram(), tempWord);
}
}
HashMapFiller fill = new HashMapFiller();
fill.hashMap(hashMap);
fill.print();
prompt.goAgain();
}
}
当 list.add 尝试添加 splitedFileArray 时会出现问题。我试着做 fileArray.length-1 但它有一个类似的错误,除了-1。
【问题讨论】:
-
您应该迭代新数组'splitedFileArra',然后您可以将拆分数组的所有部分分配到列表中。这一行是错误的:list.add(splitedFileArray[i]); 'i' 未拆分数组索引。
-
@dave 是对的。当程序编译并运行,但给出运行时异常或意外结果时,是时候进行一些调试了。如果您需要一些关于如何开始的建议,请帮助自己获取这些free debugging tips。如果您还没有熟悉 IDE 的调试器,那么现在就是绝佳机会。
标签: java arrays list file indexoutofboundsexception