简体   繁体   English

数组索引超出范围,为什么?

[英]Array index out of bound, why?

The code is rather simple but I can't figure out why I'm getting this error. 代码很简单,但我不知道为什么会收到此错误。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Project1 {

public static void main(String[] args) {
    String fileName = "States.csv";
    File file = new File(fileName);

    try {
        Scanner stream = new Scanner(file); // or use new File();
        while (stream.hasNext()){
            String data = stream.next();
            String[] values = data.split(",");
            System.out.println(values[3] + "***");
        }
        stream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

There supposely something wrong on system.out.println(values[3] - "***") and I looked but no luck. 可能是system.out.println system.out.println(values[3] - "***")出问题了,我看上去很幸运。

Because the size of the array is probably less that 4 and you are trying to print the 4th element (index 3 ) 因为array的大小可能小于4并且您试图打印第4th元素(索引3

Check your array length before print: 打印前检查array长度:

try {
    Scanner stream = new Scanner(file); // or use new File();
    while (stream.hasNext()){
        String data = stream.next();
        String[] values = data.split(",");
        if(values.length>3){
            System.out.println(values[3] + "***");
        }
        else{
            System.out.println("Desired value is missing in this row");
        }
    }
}

It seems the length of values is less than 4. That's why it is causing exception for values[3]. 似乎值的长度小于4。这就是为什么它导致values [3]异常的原因。 if you want to print the last value then you can use 如果要打印最后一个值,则可以使用

        System.out.println(values[values.length - 1] + "***");

or if you need to print the 4th index then check whether the size of value is less than 4 或者如果您需要打印第四个索引,则检查值的大小是否小于4

if(values.lenght > 3)
        System.out.println(values[3] + "***");

Please Check values hava a min length of 4. 请检查值的最小长度为4。

// For printing all splited values
for(String val : data.split(",")){
     System.out.println(val);
}

Suggestion: 建议:

Close your streams in finally block 关闭流,最后阻止

Note : The index of array starts from 0 not from 1 注意 :数组的索引从0开始而不是从1

Try looking at the data string. 尝试查看数据字符串。 The split() method split around the the comma. split()方法以逗号分隔。 If you only have one comma in your original string then the values array would only be a length of 2. 如果原始字符串中只有一个逗号,则values数组的长度仅为2。

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

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