-3

i want to extract a particular single column value of CSV file.so i had used dataset of CSV FILE having Instances:45211 and Number of Attributes:17. i had try with this code ..but its give me error like this.. "main" java.lang.ArrayIndexOutOfBoundsException: 3

pls help me...

 import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    public class Main {

        public static void main(String[] args) {
            // TODO code application logic here

            String filename ="bank-full.csv";
            File file= new File(filename);

            try {

                Scanner inputStream = new Scanner(file);
                inputStream.next();
                 while(inputStream.hasNext())
                {
                    String data= inputStream.next();
                    String[] values = data.split(",");
                   // double balance= Double.parseDouble(values[2]);
                    System.out.println(values[3]);
                }           

                    inputStream.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }
vivek patel
  • 23
  • 1
  • 7
  • Put a breakpoint at the line that throws the exception. Run the class in debug mode and watch the values of variables whose access is throwing the exception. In this case it's the array. – Boris Pavlović Jan 26 '15 at 10:52
  • have you debugged, checked the actual value of 'values' ? did you check whether you used the correct separator character ? tried to iterate over the array to check the (number of) values ? – Stultuske Jan 26 '15 at 10:52
  • thanks to all its help me...im done.. – vivek patel Jan 26 '15 at 12:37

2 Answers2

1

I'm assuming you want to read one line at a time :

    Scanner inputStream = new Scanner(file);

    while(inputStream.hasNextLine())
    {
        String data = inputStream.nextLine();
        String[] values = data.split(",");
        System.out.println(values[3]); // now, this line is safe only if you are 
                                       // sure that each row would have at least 3 commas
    }  
Eran
  • 387,369
  • 54
  • 702
  • 768
0

(1) Are you sure the delimeter in the file is a comma?

(2) Can there be empty "columns" in the file? If there are, use the following to do the split:

String[] values = data.split(",", -1);
Ofer Lando
  • 814
  • 7
  • 12