简体   繁体   中英

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.

Because the size of the array is probably less that 4 and you are trying to print the 4th element (index 3 )

Check your array length before print:

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]. 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

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

Please Check values hava a min length of 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

Try looking at the data string. The split() method split around the the comma. If you only have one comma in your original string then the values array would only be a length of 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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