有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组。lang.ArrayIndexOutofBounds异常:4

我正在groovy中致力于将值从一个选项卡分隔的文本文件提取到一个列表中。但是我遇到了ArrayIndexOutOfBoundsException

代码

println("Reading File Contents")

def fullArray = new String[31721][4]
def availableArray = new String[1386][2]
def filteredFullArray = new String[1386][5]

String fileContents = new File('beliefs.txt').text
String availableContents = new File('available.txt').text

def count = 0

fileContents.eachLine { line ->

    String[] str
    str = line.split('\t')

    def subCount = 0
    for (subCount; subCount < str.length; subCount++) {
         fullArray[count][subCount] = str[subCount]
    }
    count++
}

信仰。txt

1   Azerbaijan  hasOfficialLanguage Azerbaijani_language
2   Augustus    hasChild    Julia_the_Elder
3   Arthur_Aikin    isCitizenOf England
4   Arthur_Aikin    diedIn  London
5   Alexander_III_of_Russia isMarriedTo Maria_Feodorovna__Dagmar_of_Denmark_
6   Alexander_III_of_Russia hasChild    Nicholas_II_of_Russia
7   Alexander_III_of_Russia hasChild    Grand_Duke_Michael_Alexandrovich_of_Russia
8   Alexander_III_of_Russia hasChild    Grand_Duchess_Olga_Alexandrovna_of_Russia
9   Alexander_III_of_Russia hasChild    Grand_Duke_Alexander_Alexandrovich_of_Russia
10  Alexander_III_of_Russia hasChild    Grand_Duke_George_Alexandrovich_of_Russia
...
...
...
31719   Minqi_Li    isKnownFor  Chinese_New_Left
31720   Henry_Bates_Grubb   isKnownFor  Mount_Hope_Estate
31721   Thomas_Kuhn isKnownFor  Paradigm_shift  

运行此命令会导致以下错误

Caught: java.lang.ArrayIndexOutOfBoundsException: 4 java.lang.ArrayIndexOutOfBoundsException: 4 at extractBeliefs$_run_closure1.doCall(extractBeliefs.groovy:19) at extractBeliefs.run(extractBeliefs.groovy:12)

我知道发生上述错误的原因。但是,由于我的数组没有超过最后一个索引,并且错误显示在fileContents.eachLine { line ->行,因此我无法找到错误所在

我们将非常感谢您在这方面提出的任何建议


共 (3) 个答案

  1. # 1 楼答案

    更好的方法是先用单个空格替换所有多空格或制表符,然后用单个空格分割

    line = line.replace("\\s+/g", " ")
    str = line.split('\\s+')
    
  2. # 2 楼答案

    您的初始错误来自此行(19):

    fullArray[count][subCount] = str[subCount]
    

    第12行只是在异常退出闭包时提升异常。这肯定表明您在一行上有一个额外的选项卡。。。出于调试目的,在尝试将该行加载到阵列之前,请尝试将其打印到控制台。这将帮助您确定哪一行有错误

  3. # 3 楼答案

    尝试用空格分割

    str = line.split('\s+')
    

    而不是

    str = line.split('\t')