【问题标题】:ArrayIndexOutOfBounds when trying to add to list from string array尝试从字符串数组添加到列表时的 ArrayIndexOutOfBounds
【发布时间】: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


【解决方案1】:

此问题的根本原因是您试图访问下一行中的数组。在幕后实际发生的是,您实际上尝试访问从 split() 方法返回的未知大小的数组。返回的数组大小可能小于定义的索引(在您的情况下为i)。

list.add(splitedFileArray[i]);

您可以通过以下方式解决此问题..

for (int i = 0; i < fileArray.length; i++) {
    String[] splitedFileArray = fileArray[i].split("\\s+");
    list.addAll(Arrays.asList(splitedFileArray));
}

希望这个答案能帮助您解决问题...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2018-10-26
    相关资源
    最近更新 更多