user3211562
user3211562

Reputation: 67

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.

Upvotes: 0

Views: 763

Answers (4)

Baby
Baby

Reputation: 5102

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");
        }
    }
}

Upvotes: 5

user2535749
user2535749

Reputation: 35

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.

Upvotes: 0

Rakesh KR
Rakesh KR

Reputation: 6527

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

Upvotes: 0

stinepike
stinepike

Reputation: 54722

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] + "***");

Upvotes: 0

Related Questions