Question

In: Computer Science

Using Java Create two exception classes to capture the improper entering of coin names and their...

Using Java

Create two exception classes to capture the improper entering of coin names and their corresponding values. Name one class CoinNameException and the other CoinValueException

Design and write a program that asks a young child to input a set of coin names and their corresponding values (in cents) in their piggybank. The program should work in a loop:

  1. First, the program should prompt the child to enter the name of a coin (penny, nickel, dime, quarter, or half-dollar).
    • If an improper name for a coin is entered, then catch a CoinNameException exception, print an error message, and give the child a second chance to reenter it.
    • After two chances, terminate the program.
  2. Once a valid coin name has been entered in step #1 above, the child must then enter the corresponding value of that coin in cents (1, 5, 10, 25, or 50).
    • Use either the parseInt() or the nextInt() method to get the value of the coin.
      • Hint: What exceptions can these methods throw?
    • If the child enters the wrong value for the coin, then catch a CoinValueException exception, print an error message, and give the child a second chance to reenter the value of the coin.
    • After two chances, terminate the program.
  3. If a valid coin and its corresponding value are entered, add that coin to the child’s piggybank total and go back to step #1
  4. Other than entering an invalid coin name or value twice, provide a nicer and simpler way for the child to exit the loop above (steps 1 – 3)
  5. When the child is finished entering coins (or the program terminates), display a nicely-formatted report showing the name, value, and quantity of each coin in the child’s piggybank, along with the total value of all coins.

All exception classes should have at least two constructors:

  • one which takes no arguments and provides a default Exception message
  • another which takes a String as an argument and sets the contents of the String as the Exception message

Solutions

Expert Solution

Thanks for the question.

Below is the code you will be needing  Let me know if you have any doubts or if you need anything to change.

Thank You !!
​​​​​​​
===========================================================================

public class CoinValueException extends  Exception{

    public CoinValueException(String message) {
        super(message);
    }
}

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

public class CoinNameException extends Exception {

    public CoinNameException(String message) {
        super(message);
    }

}

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

import java.util.Scanner;

public class PiggyBank {


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

    public static void main(String[] args) {

        int[] coins = new int[5];
        String name = "";
        int count = 0;
        while (true) {


            for (int attempts = 1; attempts <= 2; attempts++) {
                try {
                    name = getCoinName();
                    break;
                } catch (CoinNameException e) {
                    System.out.println(e.getMessage());
                    if (attempts == 2) {
                        System.out.println("Max attempts reached.\nPiggy Bank will close now.");
                        System.exit(1);
                    }
                }
            }

            for (int attempts = 1; attempts <= 2; attempts++) {
                try {
                    count = getCoinValue();
                    break;
                } catch (CoinValueException e) {
                    System.out.println(e.getMessage());
                    if (attempts == 2) {
                        System.out.println("Max attempts reached.\nPiggy Bank will close now.");
                        System.exit(1);
                    }
                }
            }
            if (name.equalsIgnoreCase("penny")) coins[0]+=count;
            else if (name.equalsIgnoreCase("nickel")) coins[1]+=count;
            else if (name.equalsIgnoreCase("dime")) coins[2]+=count;
            else if (name.equalsIgnoreCase("quarter")) coins[3]+=count;
            else if (name.equalsIgnoreCase("half-dollar")) coins[4]+=count;

            System.out.print("Do you want to add another coin: (yes/no)? ");
            String again = scanner.nextLine();
            if (again.equalsIgnoreCase("no")) break;
        }

        printCollections(coins);

    }

    private static void printCollections(int[] coins) {

        System.out.println("Piggy Bank Collection");
        System.out.println("=====================\n");
        System.out.println("Pennies     : " + coins[0]);
        System.out.println("Nickel      : " + coins[1]);
        System.out.println("Dime        : " + coins[2]);
        System.out.println("Quarter     : " + coins[3]);
        System.out.println("Half-Dollar : " + coins[4]);

        double amount = coins[0] * 0.01 + coins[1] * .05 + coins[2] * .10 + coins[3] * .25 + coins[4] * .5;
        System.out.println("Total Amount: $" + amount);

    }

    private static int getCoinValue() throws CoinValueException {

        System.out.print("Enter the number of coins: ");
        try {
            int count = scanner.nextInt();
            scanner.nextLine();
            if (count < 0) throw new CoinValueException("ERROR: Count is in negative.");
            else return count;
        } catch (NumberFormatException e) {
            throw new CoinValueException("ERROR: Input is not a number.");
        }

    }


    private static String getCoinName() throws CoinNameException {

        System.out.print("Enter coin name [penny,nickel,dime,quarter,half-dollar]: ");
        String name = scanner.nextLine();
        if (name.equalsIgnoreCase("penny") ||
                name.equalsIgnoreCase("nickel") ||
                name.equalsIgnoreCase("dime") ||
                name.equalsIgnoreCase("quarter") ||
                name.equalsIgnoreCase("half-dollar")) {
            return name.toLowerCase();
        } else {
            throw new CoinNameException("ERROR: Invalid coin name: " + name + " entered.");
        }

    }


}

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


Related Solutions

Create a java program that: - Has a class that defines an exception -Have that exception...
Create a java program that: - Has a class that defines an exception -Have that exception throw(n) in one method, and be caught and handled in another one. -Has a program that always continues even if incorrect data is entered by the user -has a minimum of 2 classes in it
FlashCards with Classes and Exception Handling – Project Project Overview Create at least 2 object classes...
FlashCards with Classes and Exception Handling – Project Project Overview Create at least 2 object classes (Session and Problems) and one driver class and ensure the user inputs cannot cause the system to fail by using exception handling. Overview from Project . Implement a Java program that creates math flashcards for elementary grade students. User will enter his/her name, the type (+,-, *, /), the range of the factors to be used in the problems, and the number of problems...
Create a Java program that asks a user to enter two file names. The program will...
Create a Java program that asks a user to enter two file names. The program will read in two files and do a matrix multiplication. Check to make sure the files exist. first input is the name of the first file and it has 2 (length) 4 5 6 7 Second input is the name of the second file and it has 2 (length) 6 7 8 9 try catch method
Using a minimum of 2 classes create a java program that writes data to a file...
Using a minimum of 2 classes create a java program that writes data to a file when stopped and reads data from a file when started. The data should be in a readable format and the program should work in a way that stopping and starting is irrelevant (e.g. all data doesn't have to save just the important elements.) Program should be unique and semi-complex in some way.
Java program Create two classes based on the java code below. One class for the main...
Java program Create two classes based on the java code below. One class for the main method (named InvestmentTest) and the other is an Investment class. The InvestmentTest class has a main method and the Investment class consists of the necessary methods and fields for each investment as described below. 1.The Investment class has the following members: a. At least six private fields (instance variables) to store an Investment name, number of shares, buying price, selling price, and buying commission...
Using Eclipse IDE Create a Java Program/Class named MonthNames that will display the Month names using...
Using Eclipse IDE Create a Java Program/Class named MonthNames that will display the Month names using an array. 1. Create an array of string named MONTHS and assign it the values "January" through "December". All 12 months need to be in the array with the first element being "January", then "February", etc. 2. Using a loop, prompt me to enter an int variable of 1-12 to display the Month of the Year. Once you have the value, the program needs...
Using JAVA: This assignment is about aggregation and class collaboration. You will create several Classes that...
Using JAVA: This assignment is about aggregation and class collaboration. You will create several Classes that will be part of an overall class named InstrumentDisplay. The classes are FuelGage, Odometer, MilesSinceLastGas, and CruisingRange. The FuelGage should assume a 15 gallon tank of gasoline and an average consumption of 1 gallon every 28 miles. It should increment in 1 gallon steps when you "add gas to the tank". It should decrement by 1 every 28 miles. It should display its current...
5.9 Online shopping cart (Java) Create a program using classes that does the following in the...
5.9 Online shopping cart (Java) Create a program using classes that does the following in the zyLabs developer below. For this lab, you will be working with two different class files. To switch files, look for where it says "Current File" at the top of the developer window. Click the current file name, then select the file you need. (1) Create two files to submit: ItemToPurchase.java - Class definition ShoppingCartPrinter.java - Contains main() method Build the ItemToPurchase class with the...
Create a table of the different classes of neurotransmitters . List names of neurotransmitters, their main...
Create a table of the different classes of neurotransmitters . List names of neurotransmitters, their main functions and implications in human disease.
Create a table of the different classes of neurotransmitters. List names of neurotransmitters, their implications in...
Create a table of the different classes of neurotransmitters. List names of neurotransmitters, their implications in human disease,  and their main functions .
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT