Java Trouble with Buffered Reader and Exceptions in Java?

  • Thread starter Thread starter smilesofmiles
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
The discussion revolves around troubleshooting issues with Java code that utilizes a BufferedReader to read data from a file named "data.txt" and calculate a weighted average. The user is experiencing difficulties executing the code, despite having created the data file with the correct content. They have implemented exception handling but are unsure if it's being used correctly. Key points include attempts to read the file and populate arrays with the data, as well as confusion regarding the BufferedReader's functionality. A suggestion was made to check the file's existence and location, as the program may fail if the file is missing or empty. Additionally, it was noted that the program could encounter errors when trying to access elements in the array if the file does not contain the expected data.
smilesofmiles
Messages
18
Reaction score
0
Hello mathhelpboards community! I can't figure out how to get my code to execute while using buffered reader and try with resources. :-( I created a data.txt file correctly and it contains the numbers "0.5 3 10 70 90 80 20" without quotes. I added a catch IO Exception utilizing the printStackTrace function believing this would allow my program to run. I tried redoing the way I added the elements into my arrays thinking that I wasn't using buffered reader correctly. Frustration led me to google and youtube but I wasn't able to find buffered reader being used to add elements to an array. This was also my first time implementing FileWriter. I believe that portion is done correctly?

Any help, hints or points to the right direction will be greatly appreciated!

Code:
package calcweightedavgwithexceptions2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;public class CalcWeightedAvgWithExceptions2 {

    public static void main(String[] args) throws IOException {
         
        ArrayList<Double> inputValues = getData();
        double weightedAvg = calcWeightedAvg(inputValues);
        printResults(inputValues, weightedAvg);
              
    }
    
   public static ArrayList<Double> getData() throws IOException {
       File file = new File("data.txt"); //Hard code input file

       ArrayList<Double> userNumbers = new ArrayList<Double>();
       ArrayList<Double> userCopy = new ArrayList<>(userNumbers);
       
       if(file.exists()){
       try(BufferedReader buffy = new BufferedReader(new FileReader(file))) {
           /*First attempt at fixing. I tried to redo how I used buffered reader to add elements to the array.*/
           String strLine;
           String values[] = null;
           while ((strLine = buffy.readLine()) != null) {
               values = strLine.split(" ");
           }
           
           for(int i = 0; i < values.length; i++){
               userNumbers.add(Double.parseDouble(values[i]));
           }
           for (int j = 0; j < values.length; j++){
               userCopy.add(Double.parseDouble(values[j]));
           }

/* Second attempt. I kept thinking there must be something wrong with how I'm adding values to my arrays */
           /*String in;  
        
           while ((in = buffy.readLine()) != null) {
                userNumbers.add(Double.parseDouble(in));
           }
           while ((in = buffy.readLine()) != null) {
                userCopy.add(Double.parseDouble(in));
           }
          buffy.close();
*/
       }catch(FileNotFoundException fne){
            String errorString = fne.getMessage();
            System.out.println(errorString);
       }catch(IOException e){ /*I added catch IO Exception but am not sure if I'm using it properly.*/
           e.printStackTrace();
       }
       }
      
       return userNumbers;
   }
     
   public static double calcWeightedAvg( final ArrayList<Double> userNumbers){
   
       ArrayList<Double> userCopy = new ArrayList<>(userNumbers);
       int n = (int) Double.parseDouble(userCopy.get(1).toString());
       double sum = 0;
       double weight = (double) userCopy.get(0);
       userCopy.remove(0);
       userCopy.remove(1);
       
       Collections.sort(userCopy, Collections.reverseOrder());
       
       for(int i = 0 ; i < userCopy.size() - n; i++){
           sum = sum + Double.parseDouble(userCopy.get(i).toString()) * weight;
        }
       
       double avg = sum /(userCopy.size() - n); 
           
       return avg;
   }
   
   public static void printResults(ArrayList<Double> userNumbers, double weight) throws IOException{
    
       int n = (int) Double.parseDouble(userNumbers.get(1).toString());
       Scanner console = new Scanner(System.in);
       System.out.print("Please name the output file: ");
       String outputFileName = console.next();
     
       System.out.println("Your output was placed in the file " + outputFileName);
       
        try (FileWriter fw = new FileWriter(new File(outputFileName))){
            
            fw.write("The weighted average of the numbers is " + weight + ", when using the data ");
      
            for (int i = n; i < userNumbers.size(); i++) { 
                fw.write(userNumbers.get(i) + ", ");
            }
            fw.write("\nwhere " + userNumbers.get(0) + " is the weight used, ");
            
            fw.write("and the average is computed after dropping the lowest " + n + " values.\n");
            fw.flush();
            fw.close();
       }catch(FileNotFoundException fne){
            String errorString = fne.getMessage();
            System.out.println(errorString);
       }catch(IOException e){
           e.printStackTrace();
       }
    }
}
:confused:
 
Technology news on Phys.org
smilesofmiles said:
Hello mathhelpboards community! I can't figure out how to get my code to execute while using buffered reader and try with resources. :-( I created a data.txt file correctly and it contains the numbers "0.5 3 10 70 90 80 20" without quotes. I added a catch IO Exception utilizing the printStackTrace function believing this would allow my program to run. I tried redoing the way I added the elements into my arrays thinking that I wasn't using buffered reader correctly. Frustration led me to google and youtube but I wasn't able to find buffered reader being used to add elements to an array. This was also my first time implementing FileWriter. I believe that portion is done correctly?

Any help, hints or points to the right direction will be greatly appreciated!

Code:
package calcweightedavgwithexceptions2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;public class CalcWeightedAvgWithExceptions2 {

    public static void main(String[] args) throws IOException {
         
        ArrayList<Double> inputValues = getData();
        double weightedAvg = calcWeightedAvg(inputValues);
        printResults(inputValues, weightedAvg);
              
    }
    
   public static ArrayList<Double> getData() throws IOException {
       File file = new File("data.txt"); //Hard code input file

       ArrayList<Double> userNumbers = new ArrayList<Double>();
       ArrayList<Double> userCopy = new ArrayList<>(userNumbers);
       
       if(file.exists()){
       try(BufferedReader buffy = new BufferedReader(new FileReader(file))) {
           /*First attempt at fixing. I tried to redo how I used buffered reader to add elements to the array.*/
           String strLine;
           String values[] = null;
           while ((strLine = buffy.readLine()) != null) {
               values = strLine.split(" ");
           }
           
           for(int i = 0; i < values.length; i++){
               userNumbers.add(Double.parseDouble(values[i]));
           }
           for (int j = 0; j < values.length; j++){
               userCopy.add(Double.parseDouble(values[j]));
           }

/* Second attempt. I kept thinking there must be something wrong with how I'm adding values to my arrays */
           /*String in;  
        
           while ((in = buffy.readLine()) != null) {
                userNumbers.add(Double.parseDouble(in));
           }
           while ((in = buffy.readLine()) != null) {
                userCopy.add(Double.parseDouble(in));
           }
          buffy.close();
*/
       }catch(FileNotFoundException fne){
            String errorString = fne.getMessage();
            System.out.println(errorString);
       }catch(IOException e){ /*I added catch IO Exception but am not sure if I'm using it properly.*/
           e.printStackTrace();
       }
       }
      
       return userNumbers;
   }
     
   public static double calcWeightedAvg( final ArrayList<Double> userNumbers){
   
       ArrayList<Double> userCopy = new ArrayList<>(userNumbers);
       int n = (int) Double.parseDouble(userCopy.get(1).toString());
       double sum = 0;
       double weight = (double) userCopy.get(0);
       userCopy.remove(0);
       userCopy.remove(1);
       
       Collections.sort(userCopy, Collections.reverseOrder());
       
       for(int i = 0 ; i < userCopy.size() - n; i++){
           sum = sum + Double.parseDouble(userCopy.get(i).toString()) * weight;
        }
       
       double avg = sum /(userCopy.size() - n); 
           
       return avg;
   }
   
   public static void printResults(ArrayList<Double> userNumbers, double weight) throws IOException{
    
       int n = (int) Double.parseDouble(userNumbers.get(1).toString());
       Scanner console = new Scanner(System.in);
       System.out.print("Please name the output file: ");
       String outputFileName = console.next();
     
       System.out.println("Your output was placed in the file " + outputFileName);
       
        try (FileWriter fw = new FileWriter(new File(outputFileName))){
            
            fw.write("The weighted average of the numbers is " + weight + ", when using the data ");
      
            for (int i = n; i < userNumbers.size(); i++) { 
                fw.write(userNumbers.get(i) + ", ");
            }
            fw.write("\nwhere " + userNumbers.get(0) + " is the weight used, ");
            
            fw.write("and the average is computed after dropping the lowest " + n + " values.\n");
            fw.flush();
            fw.close();
       }catch(FileNotFoundException fne){
            String errorString = fne.getMessage();
            System.out.println(errorString);
       }catch(IOException e){
           e.printStackTrace();
       }
    }
}
:confused:

Hey smilesofmiles! ;)

Your code seems to run fine.
What is the problem?
 
Hello I like Serena! When I run my program it fails. I keep encountering this message. The last program I made with exceptions didn't have any error messages. Thank you for answering me! :-) View attachment 5797
 

Attachments

  • Error.JPG
    Error.JPG
    32.6 KB · Views: 100
smilesofmiles said:
Hello I like Serena! When I run my program it fails. I keep encountering this message. The last program I made with exceptions didn't have any error messages. Thank you for answering me! :-)

That would happen if the data.txt file is not there, or it's in the wrong location, or if it's empty.
You may want to remove the [m]if(file.exists())[/m], so that a missing file gets reported.

Note that the exception is only later in the code when it tries to access the 2nd number that is simply not there.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Back
Top