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...
Download the following zip file Bag and complete the program. You will need to complete files...
Download the following zip file Bag and complete the program. You will need to complete files MyBag and . MyBag uses the java API class ArrayList as the underline data structure. Using the class variables given, complete the methods of the MyBag class. In your BagHand class you should set appropriate default values for select class variables in the constructor in the add method, use the MyBag object to add a PlayingCard type to the bag and find and set...
Write a program that contains a main method and another method named userName. The main method...
Write a program that contains a main method and another method named userName. The main method should prompt the user to enter a full name. The userName method takes the full name as an argument and prints the name in reverse order and returns the number of characters in the name. See Sample Output (input shown in blue). Sample Output Please enter your FULL name Billy Joe McCallister Here is the name Billy Joe McCallister in reverse: retsillaCcM eoJ ylliB...
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...
Java Linked Lists I want a simple program that reads two text files that contains an...
Java Linked Lists I want a simple program that reads two text files that contains an integers matrix and store each file into a linked lists matrix so I can later preform operations such as addition and subtraction on the matrices an example of the input text files: sample a 2 6 2 6 2 18 17 11 20 sample b 3 13 5 4 11 20 13 18 20
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...
The objective of this homework assignment is to demonstrate proficiency with reading files, and using string...
The objective of this homework assignment is to demonstrate proficiency with reading files, and using string methods to slice strings, working with dictionaries and using-step wise development to complete your program. Python is an excellent tool for reading text files and parsing (i.e. filtering) the data. Your assignment is to write a Python program in four steps that reads a Linux authentication log file, identifies the user names used in failed password attempts and counts the times each user name...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT