Question

JAVA (Don't make it too complicated) Write a program that prompts the user for the name...

JAVA (Don't make it too complicated) Write a program that prompts the user for the name of a text file. The file should consist of a sequence of integers, one integer per line. The program will read in each line (using nextLine()), parse it as an int (using Integer.parseInt()), and report the number of values and their average. The average should be computed as a double.

Your program should do some basic exception handling:

(1) If the file cannot be found then the program should print a message to that effect and terminate by executing System.exit(1).

(2) If the file can be found then every time that the program reads in a line that cannot be parsed (i.e. Integer.parseInt() throws a NumberFormatException) the program should print an error message with the bad line.

The final printout should display the number of good (i.e. parsable) lines, the average of the parsable values as a double, and the number of bad (unparsable) lines. Two sample runs are shown below:

  • Enter name of input file: numbers.txt

  • Cannot parse eight as an integer.

  • Cannot parse seven as an integer.

  • Cannot parse eighty-five thousand and sixty-two as an integer.

  • Cannot parse 13 98 as an integer.

  • Number of parsable lines: 6

  • Average value: 80.83333333333333

  • Number of unparsable lines: 4

  • Enter name of input file: Nums.txt

  • Could not find file: Nums.txt

The values in numbers.txt were as follows:

•5
• 15

• 312

Homework Answers

Answer #1
Thanks for the question.

Here is the completed code for this problem. 

Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. 

If you are satisfied with the solution, please rate the answer. Thanks


===========================================================================

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

public class GameItemTest {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter name of input file: ");
        String fileName = scanner.nextLine();

        double total = 0;
        int countIntegers = 0;
        int unParsableLines = 0;
        try {
            Scanner fileReader = new Scanner(new File(fileName));
            while (fileReader.hasNext()) {
                String line = fileReader.nextLine();
                try {
                    int toInteger = Integer.parseInt(line);
                    total += toInteger;
                    countIntegers += 1;
                } catch (NumberFormatException nfe) {
                    //program should print an error message with the bad line.
                    System.out.println("Cannot parse " + line + " as an integer.");
                    unParsableLines++;
                }
            }
            //The final printout
            System.out.println("Number of parasable lines: " + countIntegers);
            if (countIntegers != 0) {
                System.out.println("Average of all integers: " + (total / countIntegers));
            }
            System.out.println("Number of unparsable lines: " + unParsableLines);
            fileReader.close();
        } catch (FileNotFoundException e) {
            //(1) If the file cannot be found then the program should
            // print a message to that effect and terminate by executing
            // System.exit(1).
            System.out.println("Could not find file: " + fileName);
            System.exit(1);
        }

    }

}

=================================================================

Know the answer?
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
Similar Questions
Collapse Write a program that prompts the user to input a positive integer. It should then...
Collapse Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (Note: An even number is prime if it is 2. An odd integer is prime if it is not divisible by any odd integer less than or equal to the square root of the number.) Turn in: Your source code for with The name of your program as a comment at the top...
Write a program that prompts the user to enter an integer number between 1 and 999....
Write a program that prompts the user to enter an integer number between 1 and 999. The program displays the sum of all digits in the integer if the input is valid; otherwise, it displays a message indicating that the integer is not between 1 and 999 and hence, is invalid. Name the program file Q1.cpp Example: if the user enters 12, sum of digits is 3. If the user enters 122, sum of digits is 5.
Program Behavior Each time your program is run, it will prompt the user to enter the...
Program Behavior Each time your program is run, it will prompt the user to enter the name of an input file to analyze. It will then read and analyze the contents of the input file, then print the results. Here is a sample run of the program. User input is shown in red. Let's analyze some text! Enter file name: sample.txt Number of lines: 21 Number of words: 184 Number of long words: 49 Number of sentences: 14 Number of...
IN JAVA 1. Write up a small program that accepts two integers from the user. Print...
IN JAVA 1. Write up a small program that accepts two integers from the user. Print which of the two values is bigger. If they are the same, print that they are the same. 2. Write a method that accepts three doubles. Calculate and return the average of the three passed double values. 3. Write up a method that accepts a score between 0-10. Print out a message according to the following table. You ay personally decide the boundaries. i.e.,...
You will write a program that loops until the user selects 0 to exit. In the...
You will write a program that loops until the user selects 0 to exit. In the loop the user interactively selects a menu choice to compress or decompress a file. There are three menu options: Option 0: allows the user to exit the program. Option 1: allows the user to compress the specified input file and store the result in an output file. Option 2: allows the user to decompress the specified input file and store the result in an...
Binary Search Tree Code in Java Write a program that prompts user to enter however many...
Binary Search Tree Code in Java Write a program that prompts user to enter however many numbers they want to add to the binary search tree. Then have the user input numbers until the tree contains that many elements. If the user enters a number that already exists in the tree, then a message should be displayed "Number is already in the tree". Once all elements are added to the tree print its contents in sorted order. Assume all user...
You shall write a Java program that functions similarly to the GNU strings utility. Your program...
You shall write a Java program that functions similarly to the GNU strings utility. Your program must: 1.Accept any number of command-line arguments, assumed to be file paths. -If the first command-line argument can be parsed as an integer, this integer shall represent the minimum sequence length. Otherwise, the minimum sequence length shall be 4 strings. 2.Print, one per line, to standard output, all printable character sequences that are at least as long as the minimum sequence length and are...
Write a program in C that takes a file name as the argument on the command...
Write a program in C that takes a file name as the argument on the command line, and, if the file is a symbolic link, prints out the contents of that link (i.e. the file name that the link points to). If it is not a symbolic link, the program should print an error int main ( int argc , char * argv [] ) { // Check if the user gave an argument , otherwise print " ERROR :...
Goals: Write a program that uses binary files. Write a program that stores records to a...
Goals: Write a program that uses binary files. Write a program that stores records to a binary file. C++ Requirements: Write a program that includes a structure named Part that contains the following fields: name - a character array of 20 elements that stores the name of the part. qty - an integer that stores the number of parts in stock. price - a double that stores the price of the part. Create three Part variables in main, and fill...
Python: Write a program that prompts the user to enter a positive integer value, and compute...
Python: Write a program that prompts the user to enter a positive integer value, and compute the following sequence: • If the value is even, halve it. • If it's odd, multiply by 3 and add 1. • Repeat this process until the value is 1, printing out each value. • Then print out how many of these operations you performed. If the input value is less than 1, print a message containing the word Error and exit the program....
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT