Question

In: Computer Science

Download and review the PrintNumbers.java program provided in the homework files. This program contains a method...

Download and review the PrintNumbers.java program provided in the homework files. This program contains a method which is designed to read in a number from the user and print it to the screen. The parameter to the method specifies whether the number might contain decimals.

There are two helper methods- one that reads in an integer and one that reads in a double.

Run the program. As written, it works as long as the user enters what they are supposed to enter! But if the user enters in a String, or a number with decimals when an integer number is required, the program crashes.

You will modify this program so that when the user enters bad input, the program gives an error message and then allows the user to try again.

Bad input is defined as: non-numeric input or numeric input with a decimal when a decimal is not allowed.

To modify the program, add one or more of each of the following to either the printNumbers method or the two helper methods:

  • loop (and looping variable)
  • try/catch or try/catch/finally
  • throws clause in a method header

The revised program should run without crashing when the user enters valid or invalid input. A sample output is provided in the homework files.

For full credit, reduce duplicated/repeated code!

Given code: PrintNumbers.java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class PrintNumbers {

    private static Scanner scan = new Scanner(System.in);

    public static void main(String[] args) {
        printNumber(true);
        printNumber(false);
    }

    public static void printNumber(boolean mayContainsDecimals) {
        System.out.println("Enter a number " + (mayContainsDecimals ? "possibly with" : "without") + " decimals:");
        if (mayContainsDecimals) {
            double d = readDouble();
            System.out.println("Your number is: " + d);
        } else {
            int n = readInteger();
            System.out.println("Your non-decimal number is: " + n);
        }
    }

    private static int readInteger() {
        int number = Integer.parseInt(scan.nextLine());
        return number;
    }

    private static double readDouble() {
        double number = Double.parseDouble(scan.nextLine());
        return number;
    }
}

Solutions

Expert Solution

Here is code in java for above problem:

package com.company;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class PrintNumbers {

    private static Scanner scan = new Scanner(System.in);

    public static void main(String[] args) {
        printNumber(true);
        printNumber(false);
    }

    public static void printNumber(boolean mayContainsDecimals) {
        while(true) {
            try {
                System.out.println("Enter a number " + (mayContainsDecimals ? "possibly with" : "without") + " decimals:");
                if (mayContainsDecimals) {
                    double d = readDouble();
                    System.out.println("Your number is: " + d);
                } else {
                    int n = readInteger();
                    System.out.println("Your non-decimal number is: " + n);
                }
            }catch (Exception e){
                System.out.println("Invalid input..! Try Again");
                continue;
            }
            break;
        }
    }

    private static int readInteger() {
        int number = Integer.parseInt(scan.nextLine());
        return number;
    }

    private static double readDouble() {
        double number = Double.parseDouble(scan.nextLine());
        return number;
    }
}

Output:


Related Solutions

In this programming assignment, you will implement a SimpleWebGet program for non- interactive download of files...
In this programming assignment, you will implement a SimpleWebGet program for non- interactive download of files from the Internet. This program is very similar to wget utility in Unix/Linux environment.The synopsis of SimpleWebGet is: java SimpleWebGet URL. The URL could be either a valid link on the Internet, e.g., www.asu.edu/index.html, or gaia.cs.umass.edu/wireshark-labs/alice.txt or an invalid link, e.g., www.asu.edu/inde.html. ww.asu.edu/inde.html. The output of SimpleWebGet for valid links should be the same as wget utility in Linux, except the progress line highlighted...
This assignment uses a combination of classes and arrays. Instructions: 1) download the 3 program files...
This assignment uses a combination of classes and arrays. Instructions: 1) download the 3 program files into a new C++ project.    NOTE: if your IDE does not allow you to create projects - or you are not sure how to do it - then you may combine the two cpp files into a single file. 2) Complete the program by adding code the the class methods. You may want to study the existing code first to get a feel...
Question 1 Download the files Book.java and BookInfo.txt from Content->Chapter 12 Quiz Files. Create a BookDriver.java...
Question 1 Download the files Book.java and BookInfo.txt from Content->Chapter 12 Quiz Files. Create a BookDriver.java class with a main method. In the main method, create an ArrayList of Book objects, read in the information from BookInfo.txt and create Book objects to populate the ArrayList. After all data from the file is read in and the Book objects added to the ArrayList- print the contents of the ArrayList. Paste your BookDriver.java text (CtrlC to copy, CtrlV to paste) into the...
C programming A small company provided you three files. 1) emp.txt : this file contains list...
C programming A small company provided you three files. 1) emp.txt : this file contains list of employees where each line represents data of an employee. An employee has an id (String max length 20), last name (string max length 100), and salary (int). See the example emp.txt file. 2) dept.txt: This text file contains list of departments of the employees. Each line of the file contains an employee id (string max length 20) and department name for that employee...
Go to the Files section and download the AFE_Test file from the Datasets folder. We are...
Go to the Files section and download the AFE_Test file from the Datasets folder. We are interested in a one­tail test described in the following fashion: Ho: u < or = to 200 CFM; H1: u > 200 CFM. At 5% significance level, we can reject the null hypothesis given the sample information in AFE_Test1. we can reject the null hypothesis given the sample information in AFE_Test2. we cannot reject the null hypothesis. we can reject the null hypothesis given...
JAVA (1) Create two files to submit: Payroll.java - Class definition PayrollClient.java - Contains main() method...
JAVA (1) Create two files to submit: Payroll.java - Class definition PayrollClient.java - Contains main() method Build the Payroll class with the following specifications: 4 private fields String name - Initialized in default constructor to "John Doe" int ID - Initialized in default constructor to 9999 doulbe payRate - Initialized in default constructor to 15.0 doulbe hrWorked - Initialized in default constructor to 40 2 constructors (public) Default constructor A constructor that accepts the employee’s name, ID, and pay rate...
Edit question Write a program that merges two files as follows. The two files are in...
Edit question Write a program that merges two files as follows. The two files are in the docsharing which you can download it. One file will contain usernames(usernames.txt):foster001smith023nyuyen002...The other file will contain passwords(passwords.txt):x34rdf3ep43e4rddw32eds22...The program should create a third file matching username and passwords(usernamesPasswords.txt):foster001x34rdf3esmith023p43e4rddnyuyen002w32eds22......Give the user of your programs the option of displaying you output file. CAN ANYONE SOLVE THIS IN C
Please, Use C++ The files in question are Square.cpp, Square.h, SquareContainer.cpp, SquareContainer.h and ClassTest.cpp. Please download,...
Please, Use C++ The files in question are Square.cpp, Square.h, SquareContainer.cpp, SquareContainer.h and ClassTest.cpp. Please download, compile and run these files, and convince yourself that you understand what they do. Question Is there a problem with the fact that SquareContainer.h defines two classes? Coding (finish in 60min) - just try to finish as many as you can Add an overloaded assignment operator to the Square class. Add a "<" operator for Square objects, which returns "true" when a Square object's...
you need to submit the following files: Main.java Additionally, you need to download file ‘letter_count.csv’, that...
you need to submit the following files: Main.java Additionally, you need to download file ‘letter_count.csv’, that contains counts for characters in a text (see submission folder on iCollege) and put it into the root of related Eclipse project folder. To view your project folder through system file explorer, right-click on ‘src’ folder in the Eclipse project explorer and choose ‘Show In->System Explorer’. Consider the following Java code, that reads a .csv file: BufferedReader csvReader = new BufferedReader(new FileReader("letter_count.csv")); String currentRow...
In Linux, if a mount point is /usr and the device george/homework/files is mounted on /usr,...
In Linux, if a mount point is /usr and the device george/homework/files is mounted on /usr, what is the complete path name to access the files directory?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT