Convert the retrieved float values from external file to an array of floats .So that it matches with the method

Aarsh Patel :

I have to get values from external file and write a float method for calculating the sum of numbers retrieved from the file

I was able to write the code for reading of file and it's working as i have tested it.I was also able to make the method for summation.The problem is i am unable to convert the vales of file as required by the method

public static void main(String[] args) throws IOException{
      File file = new File("data.txt");   
      BufferedReader br = new BufferedReader(new FileReader(file)); 

      String st; 
      while ((st = br.readLine()) != null) {
      float values[]= new float[st]; // I tried this thing
      }
   }

// Method requires float values of file in an array

 public static float naiveSum(float[] values) throws IOException {               
    float s = 0;
    for(int i = 0; i < values.length; ++i)
    s += values[i];
    return s;

}

Excepted result is the sum of the numbers but nothing is in output as there is problem to convert the values as requested by the method

Jakob Em :

I expect, that you dont know how many numbers are in your file. So you should use a List to collect all the readed values, because instead of an array it has not a fixed size. I also expect that all your float values are in seperate lines.

String st;
List<Float> valueList = new ArrayList<>(); 
while ((st = br.readLine()) != null) {         
   valueList.add(Float.parseFloat(st.trim()));
}
Float[] values = new Float[valueList.size()];
values = valueList.toArray(values);

So basically the code is reading the file line by line, removing whitespace from each line, then parsing it to Float and then putting it in the valueList. In the end the valueList is converted to an array, so you can pass it to your summarize function.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97886&siteId=1