gpt4 book ai didi

java - 为什么我的数组只打印一半的值

转载 作者:行者123 更新时间:2023-12-02 08:58:09 26 4
gpt4 key购买 nike

我正在尝试从一列 csv 文件读取数据。 vermont 这个词出现了 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]

最佳答案

您只获得了一半的匹配项,因为您在每次迭代中调用 br.readLine() 方法两次,因此您使用一个返回值进行 null 检查,并使用另一个返回值sb.append().

您的循环可以重新表述如下,以便在两个地方使用相同的返回值:

    while (strLine != null)
{
strLine = br.readLine();
if (strLine==null)
break;
sb.append(strLine);
sb.append(System.lineSeparator());
list.add(strLine);
}

使用这个有点难看的语法可以使上面的内容更加简洁:

    while ((strLine = br.readLine()) != null)
{
sb.append(strLine);
sb.append(System.lineSeparator());
list.add(strLine);
}

关于java - 为什么我的数组只打印一半的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60365550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com