通过循环创建一个数组

时间:2013-08-01 02:36:07

标签: java

这是我的代码我需要帮助,如何正确地标记每个标记并将它们放在我的循环的每个循环中的数组上,以及如何获得数组的总和以及如何获得最远的值?

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

public class Data{ 
public static void main ( String[] args ) throws IOException{ 
  String Filename = "Data.txt" ; 
    String line;

      FileReader Filereader = new FileReader(Filename);
      BufferedReader input = new BufferedReader(Filereader);
      line = input.readLine(); 

      System.out.println("--- oOo ---");
      System.out.println("AVERAGE ACID LEVEL");
      System.out.println("--------------------------------------------");

        double[] nums = new double[13];
        int sum = 0;

      while ( line != null ) // continue until end of file 
      { 

        StringTokenizer token = new StringTokenizer(line);



            for ( int i = 0; i < nums.length; i++ )
           {

              String temp = input.readLine();
              nums[i] = Double.parseDouble(temp);

              System.out.println(nums[i]);
           }

      } 
      input.close(); 

} 
    }

哦!继承data.txt上的数据

5.6
6.2
6.0
5.5
5.7
6.1
7.4
5.5
5.5
6.3
6.4
4.0
6.9

任何帮助将不胜感激...... 致谢

2 个答案:

答案 0 :(得分:3)

由于您的数据值每次都在新行上,因此您不需要StringTokenizer,因为您只需从行中读取值

你也不需要在for循环中有一个嵌套的while循环,每一行都由while循环读取一次,所以基本上在你的while循环中执行此操作

  1. 读取值
  2. 添加到数组(使用ArrayList,因此可以有动态长度)
  3. 加入总和
  4. 比较它是否最近

答案 1 :(得分:0)

试试这个,

while ((line = input.readLine()) != null)

而不是

line = input.readLine(); // it having the first value

因为,您必须逐行读取文件。

while ( line != null ) // so only your loop is unbreakable

不要复制和粘贴。试着理解。

while ((line = input.readLine()) != null) // This will read the file line by line till last value.
        {
            values[i] = Double.valueOf(line); 
            i++;                          // This is for finding the total number of values from the file.
        }

        Double sampleInput = 0.0;
        for(Double valueArray : values)
        {
            sampleInput = sampleInput + valueArray; // Atlast we sum all the array values.
        }

        Double output = (double) sampleInput/values.length;