java为什么我的数组只打印一半的值
我正在尝试从一列csv文件中读取数据。“佛蒙特”一词出现了35次,但代码只输出了17次。如果需要,我可以通过直接消息或电子邮件发送Csv文件
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class csvtxt {
public static void main(String a[]){
StringBuilder sb = new StringBuilder();
String strLine = "";
List<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\dbb38\\Downloads\\customers_export_1111 - customers_export_1.csv"));
while (strLine != null)
{
strLine = br.readLine();
sb.append(strLine);
sb.append(System.lineSeparator());
strLine = br.readLine();
if (strLine==null)
break;
list.add(strLine);
}
String wordToSearchFor3 = "Vermont";
int Vermont = 0;
for(String Vermont1 : list)
{
if(Vermont1.equals(wordToSearchFor3))
{
Vermont++;
}
}
System.out.println("Vermont = " + "["+ Vermont +"]");
//
System.out.println(Arrays.toString(list.toArray()));
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}
这是我得到的输出
Vermont = [17]
[Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont, Vermont]
# 1 楼答案
您正在调用
br.readLine
两次,跳过了一半的线路。并冒着使用后最后一行null
的风险使用^{} 更容易
这不会将行分隔符添加到每一行(可以是
\n
或\r\n
甚至其他内容)不必在循环所有行之前阅读整个列表,可以执行以下操作:
此try with resources语法将确保自动关闭
lines
始终处于关闭状态,即使在IOException上也是如此# 2 楼答案
因为在每次迭代中调用
br.readLine()
方法两次,所以只能得到一半的匹配项,因此使用一个返回值进行空检查,在sb.append()
中使用另一个返回值为了在两个位置使用相同的返回值,可以按如下方式重新设置循环:
通过使用这种有点难看的语法,可以使上述内容更加简洁: