Question

In: Computer Science

You are to modify the Pez class so that all errors are handled by exceptions. The...

You are to modify the Pez class so that all errors are handled by exceptions. The constructor must be able to handle invalid parameters. The user should not be able to get a piece of candy when the Pez is empty. The user should not be able to put in more candy than the Pez can hold. I would like you to do 3 types of exceptions. One handled within the class itself, one handled by the calling method and one custom made exception. Be sure to comment in the program identifying each type of exception. You have the freedom of choosing which exception style you use where. You will need to submit 3 files, the Pez class, the custom exception class, and a tester program demonstrating that all of your exceptions work properly.

public class Pez
{
  private int candy;
  private final int MAX_PIECES = 12;
  
  public Pez()
  {
    candy = 0;
  }
  
  public Pez(int pieces) //this will need to be error-proofed
  {
    candy = pieces;
  }
  
  public int getCandy() 
  {
    return candy;
  }
  
  public void setCandy(int pieces) //this will need to be error-proofed
  {
    candy = pieces;
  }
  
  public void getAPieceOfCandy() //this will need to be error-proofed
  {
    candy = candy - 1;
  }
  
  public int fillPez() 
  {
    int piecesNeeded = MAX_PIECES - candy;
    candy = MAX_PIECES;
    return piecesNeeded;
  }
  
  public int emptyPez()
  {
    int currentPieces = candy;
    candy = 0;
    return currentPieces;
  }
  
  public void addPieces(int pieces) //this will need to be error-proofed
  {
      candy = candy + pieces;
  }
 
  public String toString()
  {
    String thisPez = "This Pez has " + candy + " pieces of candy";
    return thisPez;
  }
  
  public boolean equals(Pez pez2)
  {
    if(this.candy == pez2.candy)
      return true;
    return false;
  }
      
}

Solutions

Expert Solution

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

Note: Details about the three kinds of exception are mentioned in comments.

// Pez.java

public class Pez {

              private int candy;

              private final int MAX_PIECES = 12;

              public Pez() {

                           candy = 0;

              }

              public Pez(int pieces) {

                           /**

                           * This constructor handles the exception by itself. the setCandy()

                           * method throws IllegalArgumentException if the parameter pieces is

                           * invalid. If that exception occur, this constructor will set the value

                           * of candy to 0

                           */

                           // trying to set the pieces of candy

                           try {

                                         setCandy(pieces);

                                         // set successfully

                           } catch (IllegalArgumentException e) {

                                         // error occurred, alerting user and using default value for candy

                                         System.out.println("Invalid number of candies detected."

                                                                    + " Using a default value of 0");

                                         candy = 0;

                           }

              }

              public int getCandy() {

                           return candy;

              }

              public void setCandy(int pieces) {

                           /**

                           * throwing exception if the 'pieces' is invalid. This should be handled

                           * by the method/object calling this method

                           */

                           if (pieces < 0 || pieces > MAX_PIECES) {

                                         throw new IllegalArgumentException("Invalid number of candies");

                           }

                           candy = pieces;

              }

              public void getAPieceOfCandy() throws InvalidOperationException {

                           /**

                           * throwing custom exception if the candy is empty.This should be

                           * handled by the method/object calling this method

                           */

                           if (candy == 0) {

                                         throw new InvalidOperationException(

                                                                    "ERROR: There are no candies left");

                           }

                           candy = candy - 1;

              }

              public int fillPez() {

                           int piecesNeeded = MAX_PIECES - candy;

                           candy = MAX_PIECES;

                           return piecesNeeded;

              }

              public int emptyPez() {

                           int currentPieces = candy;

                           candy = 0;

                           return currentPieces;

              }

              public void addPieces(int pieces) throws InvalidOperationException {

                           /**

                           * throwing custom exception if the candy+pieces exceeds the limit.This

                           * should be handled by the method/object calling this method

                           */

                           if ((candy + pieces) > MAX_PIECES) {

                                         throw new InvalidOperationException(

                                                                    "ERROR: Number of candies exceed the Maximum value");

                           }

                           //also throwing exception if the pieces are negative

                           if (pieces < 0) {

                                         throw new InvalidOperationException(

                                                                    "ERROR: Invalid Number of pieces");

                           }

                           candy = candy + pieces;

              }

              public String toString() {

                           String thisPez = "This Pez has " + candy + " pieces of candy";

                           return thisPez;

              }

              public boolean equals(Pez pez2) {

                           if (this.candy == pez2.candy)

                                         return true;

                           return false;

              }

}

// custom exception class to handle exceptions occur while using

// getAPieceOfCandy and addPieces methods

class InvalidOperationException extends Exception {

              public InvalidOperationException(String ex) {

                           super(ex);

              }

}

// Test.java (a class to test the updated Pez class)

public class Test {

              public static void main(String[] args) {

                           /**

                           * below line will cause exception, but it will be handled by the

                           * constructor itself. the number of candy will be set to 0 instead of

                           * -5 and a message will be displayed

                           */

                            Pez pez = new Pez(-5);

                           /**

                           * testing getAPieceOfCandy method

                           */

                           try{

                                         System.out.println("\nTrying to get a candy when there are none.");

                                         pez.getAPieceOfCandy();

                           }catch (InvalidOperationException ex) {

                                         System.out.println(ex.getMessage());

                                         System.out.println("Exception thrown, test success");

                           }

                           /**

                           * testing addPieces method with legal values

                           */

                           try{

                                         System.out.println("\nTrying to add 12 pieces of candies.");

                                         pez.addPieces(12);

                                         System.out.println("Added without exception. Success");

                           }catch (InvalidOperationException ex) {

                                         System.out.println(ex.getMessage());

                                         System.out.println("Exception thrown, test failed");

                           }

                           /**

                           * testing addPieces method when candies exceed maximum

                           */

                           try{

                                         System.out.println("\nTrying to add 2 pieces of candies when full.");

                                         pez.addPieces(2);

                                         System.out.println("Added without exception. Error");

                           }catch (InvalidOperationException ex) {

                                         System.out.println(ex.getMessage());

                                         System.out.println("Exception thrown, test success");

                           }

                           System.out.println("Emptying candies");

                           pez.emptyPez();

                           /**

                           * testing addPieces method with negative value

                           */

                           try{

                                         System.out.println("\nTrying to add -5 pieces of candies.");

                                         pez.addPieces(-5);

                                         System.out.println("Added without exception. Error");

                           }catch (InvalidOperationException ex) {

                                         System.out.println(ex.getMessage());

                                         System.out.println("Exception thrown, test success");

                           }

              }

}

/*OUTPUT*/

Invalid number of candies detected. Using a default value of 0

Trying to get a candy when there are none.

ERROR: There are no candies left

Exception thrown, test success

Trying to add 12 pieces of candies.

Added without exception. Success

Trying to add 2 pieces of candies when full.

ERROR: Number of candies exceed the Maximum value

Exception thrown, test success

Emptying candies

Trying to add -5 pieces of candies.

ERROR: Invalid Number of pieces

Exception thrown, test success


Related Solutions

Modify the BankAccount class to throw IllegalArgumentException exceptions, create your own three exceptions types. when the...
Modify the BankAccount class to throw IllegalArgumentException exceptions, create your own three exceptions types. when the account is constructed with negative balance, when a negative amount is deposited, or when an amount that is not between 0 and the current balance is withdrawn. Write a test program that cause all three exceptions occurs and catches them all. /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { private double balance;...
Give three examples of typical types of exceptions handled by CPU's.
Give three examples of typical types of exceptions handled by CPU's.
3.2. Unfortunately, you cannot modify the Rectangle class so that it implements the Comparable interface. The...
3.2. Unfortunately, you cannot modify the Rectangle class so that it implements the Comparable interface. The Rectangle class is part of the standard library, and you cannot modify library classes. Fortunately, there is a second sort method that you can use to sort a list of objects of any class, even if the class doesn't implement the Comparable interface. Comparator<T> comp = . . .; // for example, Comparator<Rectangle> comp = new RectangleComparator(); Collections.sort(list, comp); Comparator is an interface. Therefore,...
Modify the FeetInches class so that it overloads the following operators: <= >= != Demonstrate the...
Modify the FeetInches class so that it overloads the following operators: <= >= != Demonstrate the class's capabilities in a simple program. this is what needs to be modified // Specification file for the FeetInches class #ifndef FEETINCHES_H #define FEETINCHES_H #include <iostream> using namespace std; class FeetInches; // Forward Declaration // Function Prototypes for Overloaded Stream Operators ostream &operator << (ostream &, const FeetInches &); istream &operator >> (istream &, FeetInches &); // The FeetInches class holds distances or measurements...
**** IN C++ **** 1) Modify the class pointerDataClass so the main function below is working...
**** IN C++ **** 1) Modify the class pointerDataClass so the main function below is working properly. Use deep copy. int main() { pointerDataClass list1(10); list1.insertAt(0, 50); list1.insertAt(4, 30); list1.insertAt(8, 60); cout<<"List1: " < list1.displayData(); cout<<"List 2: "< pointerDataClass list2(list1); list2.displayData(); list1.insertAt(4,100); cout<<"List1: (after insert 100 at indext 4) " < list1.displayData(); cout<<"List 2: "< list2.displayData(); return 0; } Code: #include using namespace std; class pointerDataClass { int maxSize; int length; int *p; public: pointerDataClass(int size); ~pointerDataClass(); void insertAt(int index,...
**** IN C++ **** 1) Modify the class pointerDataClass so the main function below is working...
**** IN C++ **** 1) Modify the class pointerDataClass so the main function below is working properly. Use shallow copy. int main() { pointerDataClass list1(10); list1.insertAt(0, 50); list1.insertAt(4, 30); list1.insertAt(8, 60); cout<<"List1: " < list1.displayData(); cout<<"List 2: "< pointerDataClass list2(list1); list2.displayData(); list1.insertAt(4,100); cout<<"List1: (after insert 100 at indext 4) " < list1.displayData(); cout<<"List 2: "< list2.displayData(); return 0; } Code: #include using namespace std; class pointerDataClass { int maxSize; int length; int *p; public: pointerDataClass(int size); ~pointerDataClass(); void insertAt(int index,...
Modify the GreenvilleRevenue program so that it uses the Contestant class and performs the following tasks:...
Modify the GreenvilleRevenue program so that it uses the Contestant class and performs the following tasks: The program prompts the user for the number of contestants in this year’s competition; the number must be between 0 and 30. The program continues to prompt the user until a valid value is entered. The expected revenue is calculated and displayed. The revenue is $25 per contestant. For example if there were 3 contestants, the expected revenue would be displayed as: Revenue expected...
​​​​​​This is an assignment that I'm having trouble figuring out in python: Modify Node class so...
​​​​​​This is an assignment that I'm having trouble figuring out in python: Modify Node class so it has a field called frequency and initialize it as one. Add a search function. If a number is in the list, return its frequency. Modify Insert function. Remove push, append, and insertAfter as one function called insert(self, data). If you insert a data that is already in the list, simply increase this node’s frequency. If the number is not in the list, add...
java Programming Problem 2: Pez Candy You may like the Pez candies and the wonderful dispensers...
java Programming Problem 2: Pez Candy You may like the Pez candies and the wonderful dispensers that can be customized in so many ways. In each plastic container of Pez candy, the candies are of different colors, and they are stored in random order. Assume that you like the red candies only. Take a Pez dispenser, take out all candies one by one, eat the red ones, and put the others in a spare container you have at hand. Return...
Exception handling All Exceptions that can be thrown must descend from this Java class: The getMessage(...
Exception handling All Exceptions that can be thrown must descend from this Java class: The getMessage( ) method is inherited from this class? What are the two broad catagories of Exceptions in Java? If an Exception is not a checked exception it must extend what class? What is the difference between a checked Exception and an unchecked Exception? What are the two options a programmer has when writing code that may cause a checked Exception to be thrown? Can a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT