Trouble with Buffered Reader and Exceptions in Java?

  • Java
  • Thread starter smilesofmiles
  • Start date
  • Tags
    Java
In summary: Copy.get(n-1); weight /= n; n--; } return sum/weight; } public static void printResults( final ArrayList<Double> inputValues, final double weightedAvg){ //Prints the results of the calculation System.out.println("In summary, ");
  • #1
smilesofmiles
19
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
  • #2
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?
 
  • #3
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: 79
  • #4
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.
 

FAQ: Trouble with Buffered Reader and Exceptions in Java?

What is an exception in Java?

An exception in Java is an event that occurs during the execution of a program that disrupts the normal flow of instructions. It can happen when an error or unusual condition is encountered, such as incorrect input or a file that cannot be found.

How do I handle exceptions in Java?

Exceptions in Java can be handled using try-catch blocks. The code that could potentially throw an exception is placed within the try block, while the corresponding catch block contains the code to handle the exception. Multiple catch blocks can be used to handle different types of exceptions.

What is the difference between checked and unchecked exceptions in Java?

Checked exceptions are exceptions that are checked at compile time, meaning the programmer is required to handle them in their code. Unchecked exceptions, on the other hand, are not checked at compile time and are typically caused by programming errors. They do not need to be handled explicitly but can be caught and handled if desired.

Can I create my own custom exceptions in Java?

Yes, you can create your own custom exceptions in Java by creating a class that extends the Exception class. This allows you to define specific types of exceptions that are relevant to your program and handle them accordingly.

How do I prevent exceptions from occurring in my Java code?

Exceptions can be prevented by writing robust and error-handling code. This includes validating user input, checking for potential errors, and handling them appropriately. Using try-catch blocks and creating custom exceptions can also help prevent unexpected errors from occurring in your code.

Similar threads

Replies
2
Views
2K
Replies
1
Views
2K
Replies
4
Views
2K
Replies
1
Views
1K
Replies
5
Views
2K
Replies
1
Views
2K
Replies
6
Views
2K
Back
Top