-2

I have read a csv file and put all data into a string type array and displayed that array.now i want to search a string in that array and at the end it returns the number of times that string was found in the array. my code is below

package countscv;

import com.opencsv.CSVReader;
import java.io.FileNotFoundException;

import java.io.IOException;
import javax.swing.JOptionPane;
import java.io.FileReader;
import java.util.Arrays;

public class Countscv {
    /** @param args the command line arguments */
    public static void main(String[] args) throws FileNotFoundException, IOException {

        //Build reader instance
        //Read data.csv
        //Default seperator is comma
        //Default quote character is double quote
        //Start reading from line number 2 (line numbers start from zero)
        CSVReader reader = new CSVReader(new FileReader("res.csv"), ',' , '"' , 1);

        //Read CSV line by line and use the string array as you want
        String search="Brazil";
        int counter=0;
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            if (nextLine != null) {
                //Verifying the read data here
                System.out.println(Arrays.toString(nextLine));
            }
        }
        for(int i=0;i<nextLine.length;i++)
        {
            if((nextLine[i].equals(search)))
            {
                counter++;
            }
        }
        System.out.print(counter);
    }
}

it displays the array with nullpointer exception.what could be the error?please help anyone.

SimonC
  • 6,590
  • 1
  • 23
  • 40
rushan
  • 211
  • 2
  • 6
  • 16

1 Answers1

1

The for loop is trying to use nextLine which is null at that point because the while loop has reached it end. You need to count inside the while loop. Try the following:

CSVReader reader = new CSVReader(new FileReader("res.csv"), ',' , '"' , 1);
String search = "Brazil";
int counter = 0;
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
    for(String word : nextLine) {
        if (word.equals(search)) {
            counter++;
        }
    }
}
System.out.println(counter);
stefana
  • 2,606
  • 3
  • 29
  • 47
  • it seems to be working good.thanks but where should i print the total count of the counter? outside while loop? – rushan Feb 20 '15 at 12:46
  • okay thanks this is working fine but i have one issue.my data is currently displayed in the form of array of strings(each string array for each line).How can i save all the data from my csv file to a single array and then search it? Would be of great help. – rushan Feb 20 '15 at 13:23