Question

Write a program that reads the scores from the file and displays their total and average.

Suppose that a text file Lab2.txt contains an unspecified number of scores. Write a program that reads the scores from the file and displays their total and average.In the text file, the scores are separated by blanks.

The program should contain two methods with these signatures (it can contain other methods besides these if you think appropriate):
public static double totalScores(File inFile)
public static double averageScores(File inFile)

The output from the program should look like this successful sample run from my solution:
The total of the scores is 60.7
The average of the scores is 6.07

Once you have the program working, implement exception handling to handle FileNotFoundException.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
package javaapplication4;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
public class JavaApplication4
{
     
    //List variable for storing the read scores from the file
    public static List<Double> Values;
    public static void main(String[] args)
    {
         
        //Creating File for reading
        File inFile=new File("C:\\MyData\\input\\Lab2.txt");
         
        //Initializing the List
        Values = new ArrayList<Double>();
         
        //Calling the method that calculates the Avearge
        double avg= averageScores(inFile);
        System.out.println("The average of the scores is " + avg);
    }
    public static void readFile(File inFile)
    {
        BufferedReader reader = null;
        try
        {
             
            //Inorder to read a file, 
            //we need to use FileReader and then to store the results temporarily
             
            //we need to use buffer reader
            reader = new BufferedReader(new FileReader(inFile));
            String text = null;
            // repeat until all lines is read
            while ((text = reader.readLine()) != null)
            {
                 
                //The read values will be in text format, convert them to double values
                Values.add(Double.parseDouble(text));
            }
        }
        catch (FileNotFoundException e)
        {
             
            //Handling FileNotFoundException
            System.out.println(e.getMessage());
        }
        catch (IOException e)
        {
             
            //Handling other IO and File Readingt related Exception
            System.out.println(e.getMessage());
        }
        finally
        {
            try
            {
                if (reader != null)
                {
                    reader.close();
                }
            }
            catch (IOException e)
            {
                System.out.println(e.getMessage());
            }
        }
    }
    public static double totalScores(File inFile)
    {
        double sum =0.0;
         
        //Calling File Read methods
        readFile(inFile);
         
        //Calculating the total
        for(int i=0;i<Values.size();i++)
        {
            sum += Values.get(i);
        }
        return sum;
    }
    public static double averageScores(File inFile)
    {
         
        //Calling the method which calculates the total of all scores
        double total = totalScores(inFile);
        System.out.println("The total of the scores is " + total);
        int len=Values.size();
         
        //Condition check for divide by zero error
        if(len != 0)
        {
            return total/len;
        }
        return 0.0;
    }
}


answered by: TrainWin
Add a comment
Know the answer?
Add Answer to:
Write a program that reads the scores from the file and displays their total and average.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a Java program that reads words from a text file and displays all the non-duplicate...

    Write a Java program that reads words from a text file and displays all the non-duplicate words in ascending order. The text file is passed as a command-line argument. Command line argument: test2001.txt Correct output: Words in ascending order... 1mango Salami apple banana boat zebra

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • I'm needing help writing a program that reads a list of scores from a .txt file...

    I'm needing help writing a program that reads a list of scores from a .txt file then drops the lowest. Instructions are below. Then use the "low score drop" algorithm in a program to read and process an indeterminate number of floating-point scores from a file. The program should then display the result (the lowest score in the file), with two digits after the decimal. There is no restriction on these values; they might be negative or positive, and the...

  • In C write a text analyzer program that reads any text file. The program displays a...

    In C write a text analyzer program that reads any text file. The program displays a menu that gives the user the options of counting: • Lines • Words • Characters • Sentences (one or more word ending with a period) • or all of the above Provide a separate function for each option. At the end of the analysis, write an appropriate report.

  • Write a program to read a text file, place each line it reads into an array....

    Write a program to read a text file, place each line it reads into an array. Then print the array’s contents one line at a time. Then add to the end of the text file “Success”. Use error exception handling and if the text file does not exist print "Error file not found." Always print "It worked." as part of the try clause. Upload a zip folder file of the .py and text file. roses are roses are red, violets...

  • out1.txt File Directly Below... Note: "//notaword" is the part that is not a word and needs...

    out1.txt File Directly Below... Note: "//notaword" is the part that is not a word and needs to be handled and is specifically the part I am having trouble with https://www.dropbox.com/s/ume3slnphyhi6wt/out1.txt?dl=0 - link for the out1.txt file for testing yourself Please include comments as I am in this for learning and would really appreciate the help! Write a program that reads words from a text file and displays all the words (duplicates allowed) in ascending alphabetical order. The words must start...

  • write a python program that reads from a file, scores.txt, a list of test scores. the...

    write a python program that reads from a file, scores.txt, a list of test scores. the program should calculate the average of all the scores, and print to the screen. the program should also have a function, num_passing, that takes as a parameter the list or grades and returns the number of scores that are above 64.

  • Write a Python program that reads text from a file, encrypts it with a Caesar Cipher,...

    Write a Python program that reads text from a file, encrypts it with a Caesar Cipher, and displays the encrypted text. Do not process punctuation. Convert the original string to all lower-case before encrypting it.

  • Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File;...

    Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Lab8Num1 { public static void main(String[] args) { //Declaring variable to be used for storing and for output double biggest,temp; //Creating file to read numbers File inFile = new File("lab8.txt"); //Stream to read data from file Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { //Logger.getLogger(Lab10.class.getName()).log(Level.SEVERE, null, ex); } //get first number...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT