2

文本文件如下所示:

数据,数据,数据,数据,数据
,数据,数据,数据

数据是数字。用逗号分隔的 4 个数字和大约 2000 行。但是我一次只需要使用 20 行。起始行需要通过它的编号来选择,然后它会得到 19 个额外的行。

需要将这些数据放入唯一命名的变量(浮点数)中,以便我可以对它们进行数学运算。所以可以这样命名:

DataOne1 DataOne2 DataOne3 DataOne4
DataTwo1 DataTwo2 DataTwo3 DataTwo4

这样我就可以像 DataTwo1 - DataOne3 那样做数学运算。这些变量当然总是被命名为相同的,但是我将能够通过选择新行来更改基础数据。

很抱歉,这是一个初学者的问题,但我完全无法将不同解决方案的东西放在一起以获得我的确切解决方案。

所以我的问题是我该怎么做?

4

3 回答 3

5

1. You can read the entire line using Scanner method nextLine().

2. Then use split() method (I am assuming that the data is separated by( "," )commas), to get all the 4 data on the line.

eg:

String[] s = strLine.split(",");

3. Consider making an ArrayList of Float and then convert each item in the String[] array into a Float item in ArrayList, using Float.parseFloat()

ArrayList<Float> fArr = new ArrayList<Float>();
for (String temp : s){
    fArr.add(Float.parseFloat(temp));
}

4. Then do whatever calculation you need.

于 2012-07-22T13:36:38.740 回答
0

为了得到你想要的,这些是你需要做的步骤:

1.使用以下命令打开文件BufferedReader

BufferedReader br = new BufferedReader(new FileReader(filename));

2.到达起跑线:

for (int i = 0; i < startLine; i++) {
    line = br.readLine();
}

3.处理你需要的 20 行,将数字存储在一个ArrayList<Double>

for (int i = startLine; i < startLine + 20; i++) {
   line = br.readLine();

   // Split the lines using comma as delimiter
   String[] numberStrings = line.split(",");
   ArrayList<Double> numbers= new ArrayList<Double>();

   for(String numberString : numberStrings) {
       Double number = Double.valueOf(numberString);
       numbers.add(number);
   }
   // Do calculations with them
}
于 2012-07-22T13:46:01.420 回答
0

这是代码。对于每一行,我将值存储在数组中。因此,您的 DataOne1 将在 cols0[0] 中,DataTwo1 将在 cols0[1] 中,DataTwo1 将在 cols1[0] 中,DataTwo2 将在 cols1[1] 中,依此类推。你可以很好地使用二维数组来达到这个目的,但为了简单起见,我选择了这种方法。

 try {
        BufferedReader br = new BufferedReader(new FileReader("fileName"));
        String line;
        float[] col0 = new float[20];
        float[] col1 = new float[20];
        float[] col2 = new float[20];
        float[] col3 = new float[20];
        for (int i = 0; i < 20; i++) {
            while((line = br.readLine()) != null) {
                // Since you told comma as separator.
                String[] cols = line.split(","); 
                col0[i] = Float.valueOf(cols[0]);
                col1[i] = Float.valueOf(cols[1]);
                col2[i] = Float.valueOf(cols[2]);
                col3[i] = Float.valueOf(cols[3]);
            }
            // Do something - your math.
        }
        br.close();
    }
    catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
于 2012-07-22T13:49:41.030 回答