我已经阅读了一个csv文件并将所有数据放入一个字符串类型数组并显示该数组。现在我想搜索该数组中的字符串,最后它返回在数组中找到该字符串的次数。我的代码在下面
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);
}
}
它显示带有nullpointer异常的数组。可能是错误?请帮助任何人。
答案 0 :(得分:1)
for循环尝试使用nextLine,因为while循环已经到达它,所以此时为null。你需要计算while循环内部。请尝试以下方法:
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);