Question

Write a Java program that reads the file "input.txt" and calculates and prints the average of...

Write a Java program that reads the file "input.txt" and calculates and prints the average of all integer numbers in this file. YOU HAVE TO WRITE 2 VERSIONS: one that throws the FileNotFoundException exception and one that handles the exception (try/catch). Also, make sure that your programs handle (consume) unwanted input. Test your programs in a similar fashion to the output samples listed below.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class AverageInFile {

    public static void main(String[] args) {
        File file = new File("input.txt");
        try {
            Scanner fin = new Scanner(file);
            double total = 0, count = 0;
            while (fin.hasNextInt()) {
                total += fin.nextInt();
                ++count;
            }
            System.out.println("Average is " + (total/count));
            fin.close();
        } catch (FileNotFoundException e) {
            System.out.println(file.getAbsolutePath() + " is not found!");
        }
    }
}

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class AverageInFile {

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("input.txt");
        Scanner fin = new Scanner(file);
        double total = 0, count = 0;
        while (fin.hasNextInt()) {
            total += fin.nextInt();
            ++count;
        }
        System.out.println("Average is " + (total / count));
        fin.close();
    }
}
Add a comment
Know the answer?
Add Answer to:
Write a Java program that reads the file "input.txt" and calculates and prints the average of...
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
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