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: 102
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.
 
Thread 'Star maps using Blender'
Blender just recently dropped a new version, 4.5(with 5.0 on the horizon), and within it was a new feature for which I immediately thought of a use for. The new feature was a .csv importer for Geometry nodes. Geometry nodes are a method of modelling that uses a node tree to create 3D models which offers more flexibility than straight modeling does. The .csv importer node allows you to bring in a .csv file and use the data in it to control aspects of your model. So for example, if you...
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...

Similar threads

Back
Top