0

i have been given a file full of details and have to extract it and store into different arrays of objects according to its respective column. The tricky thing is, not all lines have the same amount of data. I can read the file, i can split it and everything.

20005,Arsenal,ManU,Arsenal,WestHam,Y,2,3,40000
2006,ManU,Chelsea,ManU,WestHam,N
2007,ManU,Arsenal,ManU,WestHam,Y,1,0,260000
2008,Chelsea,ManU,Chelsea,Swansea,Y,4,0,285630
2009,Chelsea,ManCity,Chelsea,Swansea,N

I can store everything into arrays up to column 6, after that, for some lines, information is not given, thats when i get the error from eclipse. How would i go about fixing that?

Here is my code: (Not posting all of it as this is an assignment and people are probably looking for answers and i dont want to be caught for collusion)

try{ 
Scanner kd = new Scanner(file);
    while(kd.hasNext()){
        String data = kd.nextLine();
        String [] values = data.split(",");
        String year = values[0];
        String winningscore= values[6];

i get this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at GrandFinal.<init>(GrandFinal.java:19)
at MainClass.main(MainClass.java:11)
roro
  • 713
  • 2
  • 6
  • 19
  • 2
    (a) Use a [CSV Parser](http://stackoverflow.com/questions/101100/csv-api-for-java) (b) Or use a condition: `if (values.length > 6) String winningscore= values[6];` – assylias May 29 '13 at 14:17

3 Answers3

1

Check for the length of the array!

if(value.length > 6){
    // messages are given
} else {
    // messages are not given
}

Or, maybe, according to the data you gave:

if(value[5].equals("Y")){
    // messages are given
} else {
    // messages are not given
}
johnchen902
  • 9,531
  • 1
  • 27
  • 69
1

You need to check if the values array is long enough.

if(values.length > 0){
     String year = values[0];
}
if(values.length > 6){ 
 //values.length == 6 means the last element you can access is number 5. 
     String year = values[6];
}
zetches
  • 148
  • 8
1

For the line bellow:

2007,ManU,Arsenal,ManU,WestHam,Y,1,0,260000

if 1 is the 6 th element for you just do:

  if(values.length > 6) {
       String winningscore= values[6];
  }

if 1,0,260000 is your 6 th element then, it should be:

  String winningScoreString = "";

  if(values.length > 6 ) {
       winningScoreString+= values[6];
  }

  if(values.length > 7 ) {
       winningScoreString+= "," + values[7];
  }

  if(values.length > 8 ) {
       winningScoreString+= "," + values[8];
  }
Sazzadur Rahaman
  • 6,938
  • 1
  • 30
  • 52