-1
for (int k = 0; k < dec2.length; k++) {
    System.out.println(dec2[k]);
    String[] tab = dec2[k].split(",");
    System.out.println(tab[0]);

When I try this code, dec2 is a String array containing:

41,31
11,21
42,41
12,22

When I try to display tab[0], I get the first number (before the ","), but tab[1] returns an ArrayIndexOutOfBoundsException, and I don't get why since it's supposed to contain the 2nd number (after the ",").

Redtama
  • 1,603
  • 1
  • 18
  • 35
FreeRide
  • 27
  • 4

2 Answers2

1
String[] dec2 = new String[] {"41,31", "11,21", "42,41", "12,22"};
for(int k = 0 ; k < dec2.length ; k++) {

    System.out.println(dec2[k]);
    String[] tab = dec2[k].split(",");


    System.out.println(tab[0]);
    System.out.println(tab[1]);
}

I got this output:

41,31
41
31
11,21
11
21
42,41
42
41
12,22
12
22

Process finished with exit code 0

No exceptions.

You can try to chek tab.length before get elements by index, or use forEach loop:

for(int k = 0 ; k < dec2.length ; k++) {

    System.out.println(dec2[k]);
    String[] tab = dec2[k].split(",");

    for (String part : tab) {
        System.out.println(part);
    }
}
Kirill
  • 1,540
  • 4
  • 18
  • 41
0

Try this solution:

  for(int k = 0 ; k < dec2.length ; k++){

        System.out.println(dec2[k]);
        String [] tab = dec2[k].split(",");
        for (String string : tab) {
            System.out.print(string+" ");
        }
        System.out.println();

}

I create a foreach loop to iterate the array tab to exract both number like:

  for (String string : tab) {
            System.out.print(string+" ");
        }

Output:

41,31
41 31
11,21
11 21
42,41
42 41
12,22
12 22 

And if you want use exact index try this you'll havr the same output:

 for(int k = 0 ; k < dec2.length ; k++){

        System.out.println(dec2[k]);
        String [] tab = dec2[k].split(",");
            System.out.print(tab[0]+" ");
            System.out.print(tab[1]);
        System.out.println();

    }
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
  • While this does work, I think OP will find an underlying issue like poorly formatted input. I feel this treats the symptom, not the cause. – Clark Kent Dec 23 '15 at 14:40
  • When i just print it like you did, everything seems to work, but when i try to access an exact index of tab it doesn't seem to work, i don't get why. – FreeRide Dec 23 '15 at 15:03
  • @BBaldwin I tested it with exact index and seems work, see the answer above – Abdelhak Dec 23 '15 at 15:38