简体   繁体   中英

Printing a bidimensional array (generated with split) in Java

So solved this problem but now, after I figured out how to split my String into an array, I want this array to be bi-dimensional. And when I want to print the second dimension I receive

java.lang.ArrayIndexOutOfBoundsException: 17
at IOControl.ReadCsvFile.fillIndex(ReadCsvFile.java:17)
at IOControl.ReadCsvFile.<init>(ReadCsvFile.java:89)
at en.window.Main.main(Main.java:48)

I figured out it's because i'm reading too far in my array... but why? My array-declaration :

        String index[][] = new String [data.length()][data.length()];

This is how i fill & print the bidimensionnal array :

private void fillIndex(String[][] index, String data, int j)
{
    //index is empty, data is my String (read line by line)
    //j is the iterator i use for the second dimension of the array
    index[j] = data.split(";");
    for(int i = 0; i < data.length(); i++)
    {
        System.out.println("[" +j+ "][" +i+ "] = " +index[j][i]);           
    }
}

Use index[j].length instead of data.length() .

The number of items is index[j].length = data.split(";").length

My guess would be that it is in the for loop, try changing it to this:

index[j] = data.split(";");
for(int i = 0; i < index[j].length; i++)
{
    System.out.println("[" +j+ "][" +i+ "] = " +index[j][i]);           
}

You want to iterate through each part of index[j] NOT data .

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