【问题标题】:Why last value in a csv keeps repeating itself when reading from为什么csv中的最后一个值在读取时不断重复
【发布时间】:2013-06-22 02:45:04
【问题描述】:

这是我已经搞砸了一天的功能。出于某种原因,它一遍又一遍地在 csv 中写入最后一个值,而不是通过行解析。我输入了一些打印语句,看起来行内容正确写入数组,但被最后一个值覆盖。任何帮助都会很棒,谢谢。

public int csvCombine(ArrayList <Indexstruct> todaysCSV, int totalconvo, String date) throws IOException{   
String rows = null;
Indexstruct templist=new Indexstruct();
String [] rowArray= new String [2];

FileReader fr = new FileReader(date + ".csv");
BufferedReader br = new BufferedReader(fr);

rows= br.readLine();
rowArray=rows.split(",");
totalconvo+=Integer.parseInt(rowArray[0]);      //Reads in total amount of words spoken and adds it to the CSV value of words spoken
final int csvSize=Integer.parseInt(rowArray[1]);            //Read in size of csvList 

for(int count=0; count<csvSize-1; count++){
    rows = br.readLine();
    rowArray = rows.split(",");                         // Reads lines into an array, takes array values and places them into an object of type indexStruct to write into ArrayList
    templist.numOfUses=Integer.parseInt(rowArray[1]);   //sets object num of uses
    templist.Word=rowArray[0];                          //sets object word
    todaysCSV.add(count, templist);                     //adds object to csv ArrayList
    }   
br.close();
return totalconvo;
}   

【问题讨论】:

  • ...或者您可以忽略问题的答案。

标签: java csv bufferedreader


【解决方案1】:

您当前所做的只是一遍又一遍地添加相同的临时列表对象,因此所有数据都相同是有意义的。您需要在 for 循环的每次迭代中创建一个新的 templist 对象(无论它是什么类型)。

即,

for(int count=0; count < csvSize-1; count++) {
    rows = br.readLine();
    rowArray = rows.split(",");                         
    int useCount = Integer.parseInt(rowArray[1]);   
    String word = rowArray[0];                      

    // assuming a type called TempList with a constructor that looks like this
    todaysCSV.add(count, new TempList(useCount, word));    
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2018-12-02
    • 2012-10-31
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多