简体   繁体   English

Java索引超出范围错误-缺少条目

[英]Java index out of bounds error - missing entries

I'm trying to parse a csv file. 我正在尝试解析一个csv文件。 A typical line looks like this: 典型的行如下所示:

7,118.2722833,98.61084463,94.36895546,,

The problem I'm having is that when I split the line, I'm only getting an array length of 4. I would like to have the fifth and sixth elements of the array return null, but I'm getting an index out of bounds error. 我遇到的问题是,当我分割线时,我只会得到4的数组长度。我想让数组的第五和第六个元素返回null,但是我从中得到索引边界错误。

Here is a reduced version of the code: 这是该代码的简化版本:

BufferedReader br = new BufferedReader(new FileReader("FileName"));
String line = "";
String[] datum = new String[6];

while ((line = br.readLine()) != null) {
    datum = line.split(",");

    if (datum[5] != "") {
        //some statements
    }
}

Any idea why it's ignoring the last 2 commas? 知道为什么它忽略了最后两个逗号吗?

The split method without any arguments will discard any trailing null elements. 没有任何参数的split方法将丢弃任何尾随的null元素。 Pass a negative limit to split , and it will return an array with trailing null elements intact. 传递负数limitsplit ,它将返回一个数组,该数组保留尾随null元素。

datum = line.split(",", -1);

Also, don't use != to see if it's the empty string; 另外,不要使用!=来查看它是否为空字符串。 use 采用

if (!("".equals(datum[5]))) {

Array index starts from 0, if you want 5th element you need to do datum[4] instead of datum[5] 数组索引从0开始,如果要第5个元素,则需要执行datum[4]而不是datum[5]

7 --------------0
118.2722833-----1
98.61084463-----2
94.36895546-----3,
 ----------------4

我建议阅读有关方法java.lang.String.split(String regex, int limit)limit参数的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM