user3670665
user3670665

Reputation: 1

I am trying to get a file to read into an arraylist, and calculate the average and print out the contents of the Arraylist and the average.

I keep getting error messages in the bufferedreader and the catch exceptions at the end. I have been at this for three days now. If somebody could please just tell me what im doing wrong and show me how to fix my code it would be greatly apreciated.

package week07;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFileChooser;


public class Week07 {


    public static void main(String args[]) throws IOException
    {

        {
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showOpenDialog(null);
        //check result
            File file = chooser.getSelectedFile();
        }
        // Use DataInputStream to read binary NOT text.
        BufferedReader br = new BufferedReader(new FileReader(file));

        String strLine;
        List<Double> numbers= new ArrayList<Double>();

        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
        // Add number from file to list 
        numbers.add( parseDecimal(strLine)); 
        }
        //Close the input stream
        ((BufferedReader) numbers).close();

        System.out.println(numbers);
    }catch (Exception e){
        e.printStackTrace();
    }


private static Double parseDecimal(String strLine) {
    // TODO Auto-generated method stub
   return null;
}
}

Upvotes: 0

Views: 204

Answers (2)

Masudul
Masudul

Reputation: 21971

Using Java-8 you can achive your goal by reducing a lot of boilerplate code. Look at below steps.

  1. Read the file into BufferedReader

    BufferedReader reader= new BufferedReader(new  FileReader(file));
    
  2. Convert file lines into String Stream

    Stream<String> lineStream=reader.lines();
    
  3. Read into List<Double>.

    List<Double> numbers =lineStream.map(p-> Double.valueOf(p))
                               .collect(Collectors.toList());
    
  4. Calculate average from List<Double>.

    double average = numbers.stream().mapToDouble(p->p).average().getAsDouble();
    
  5. Display the output.

    System.out.println(average);
    

Upvotes: 0

Aniket Thakur
Aniket Thakur

Reputation: 68955

((BufferedReader) numbers).close();

How can you typecast List to BufferedReader and then call close() on it. Obviously you will get exception. Change it to br.close() and do it preferably in finally block with a null check`.

Upvotes: 1

Related Questions