-1

我有一个 .csv 文件,并且我了解如何在 Java 中读取它,我的问题是我希望能够将文件内的值放入一个字符串中,然后读取该字符串,以便我可以计算这些值。

爱丽丝琼斯,80,90,100,95,75,85,90,100,90,92 鲍勃
曼弗雷德,98,89,87,89,9,98,7,89,98,78

这些是值,现在我如何将每个名称旁边的所有整数相加并创建一个平均值?我最大的问题是当我读取文件时,它位于 While 循环中,然后能够打印出这些行,就像它在控制台中看到的那样,但是当我想在 While 循环之外打印值时,它说字符串没有'不存在,因此如果其中没有任何内容,我无法计算这些值。

 import java.io.*;
 import java.util.*;

 public class Grades {
public static void main(String args[]) throws IOException
 {
 try{
 // Open the file that is the first 
 // command line parameter
 FileInputStream fstream = new FileInputStream("filescores.csv");


 BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
 String strLine;
 //Read File Line By Line
 while ((strLine = br.readLine()) != null)   {
 // Print the content on the console
 String line = strLine
 System.out.println (strLine);
 }
 //Close the input stream
 in.close();
 }catch (Exception e){//Catch exception if any
 System.err.println("Error: " + e.getMessage());

 }
 }
 }
4

2 回答 2

0

我建议实现一个普通的旧 java 对象(PO​​JO)并将数据存储在那里:

public class MyRow {
    public final String name;
    public final int[] values;

    public MyRow(String name, int[] values) {
        this.name=name;
        this.values=values;
    }
}

并拆分你的字符串并将其放在一个简单的List<MyRow>

MyRow splitData(String line) {
    String[] parts=line.split(" ");
    int[] vals=new int[parts.length];
    // starting with one for skipping the name
    for(int i=1; i<parts.length; i++) {
        vals[i-1]=Integer.parse(parts[i]);
    }
    return new MyRow(parts[0], vals);
}

所以基本上你的读取循环看起来像这样:

List<MyRow> data = new ArrayList<MyRow>();
while((strLine = br.readLine()) != null) {
    // Print the content on the console
    System.out.println (strLine);
    data.add(splitData(strLine));
}

现在所有数据都在data列表中。

于 2013-04-24T15:38:18.000 回答
0

当我想在 While 循环之外打印值时,它说字符串不存在

正如我评论的那样,您的代码中存在范围问题。但是,我没有看到您正在打印或执行任何操作的 while 循环之外的任何内容。您可以使用以下代码片段在 while 循环之外打印该行。

ArrayList<String> lines = new ArrayList<String>();// Updated <String>

 while ((strLine = br.readLine()) != null)   {
   // Print the content on the console
   lines.add(strLine);
   System.out.println(strLine);
 } 

for(int i = 0; i < lines.size(); i++){
 System.out.println(lines.get(i));
}

变量范围

编辑评论

注意: Grades.java 使用未经检查或不安全的操作。

注意:使用 -Xlint 重新编译:详细信息未选中。

以上只是编译器给出的警告,让您了解不安全的集合使用。 有关更多详细信息,请参见此处

于 2013-04-24T15:42:39.267 回答