Question

File Factorials.java contains a program that calls the factorial method of the MathUtils class to compute...

File Factorials.java contains a program that calls the factorial method of the MathUtils class to compute the factorials of integers entered by the user.

In this program, two things can possibly occur:

  • The program always returns 1 if negative integers are entered by the user. Returning 1 as the factorial of any negative integer is not correct.
  • The program also returns negative numbers when the user enters integers greater than 16. Returning a negative number for values over 16 also is not correct.

To correct this problem, modify it as follows:

  • Create a new exception class called NegativeArgumentException that extends IllegalArgumentException. The class has one constructor public NegativeArgumentException(String message) that takes a string as parameter.
  • Create another new exception class called TooLargeArgumentException that extends IllegalArgumentException. The class has one constructor public TooLargeArgumentException(String message) that takes a string as parameter.

In the MathUtils class:

  • Modify the header of the factorial method to indicate that factorial can throw NegativeArgumentException and TooLargeNumberException exceptions.
  • Modify the body of factorial method to check the value of the argument and, if it is negative, throw a NegativeArgumentException with the message "Factorial is undefined for negative integers" passed as parameter to the exception constructor.
  • Modify the body of factorial method to check the value of the argument and, if it is greater than 16, throw a TooLargeArgumentException with the message "Factorial is too large - overflow occurs!" passed as parameter to the exception constructor.
  • Modify the main method in your Factorials class to catch the exception thrown by factorial.

// ****************************************************************
// Factorials.java
//
// Reads integers from the user and prints the factorial of each.
//
// ****************************************************************
import java.util.Scanner;

public class Factorials
{
public static void main(String[] args)
{
   String keepGoing = "y";
   Scanner scan = new Scanner(System.in);

   while (keepGoing.equalsIgnoreCase("y"))
   {
       System.out.print("Enter an integer: ");
       int val = scan.nextInt();
      
       System.out.println("Factorial(" + val + ") = "
                   + MathUtils.factorial(val));

       System.out.print("Another factorial? (y/n) ");
       keepGoing = scan.next();
   }
}

// ****************************************************************
// MathUtils.java
//
// Provides static mathematical utility functions.
//
// ****************************************************************
public class MathUtils
{
//-------------------------------------------------------------
// Returns the factorial of the argument given
//-------------------------------------------------------------
public static int factorial(int n)
{

       int fac = 1;
       for (int i=n; i>0; i--)
       fac *= i;
       return fac;
}


}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Place each class in separate files as mentioned. 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. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

//NegativeArgumentException.java

public class NegativeArgumentException extends IllegalArgumentException {    

      //constructor taking a String message

      public NegativeArgumentException(String message) {

            // passing message to super class constructor

            super(message);

      }

}

//TooLargeArgumentException

public class TooLargeArgumentException extends IllegalArgumentException {

      // constructor taking a String message

      public TooLargeArgumentException(String message) {

            // passing message to super class constructor

            super(message);

      }

}

//MathUtils.java

public class MathUtils {

      // -------------------------------------------------------------

      // Returns the factorial of the argument given, throws

      // NegativeArgumentException if n is below 0, TooLargeArgumentException if n

      // is above 16

      // -------------------------------------------------------------

      public static int factorial(int n) throws NegativeArgumentException,

                  TooLargeArgumentException {

            //throwing exception if n is below 0

            if (n < 0) {

                  throw new NegativeArgumentException("Error: Negative value for n ("

                              + n + ")");

            }

            //throwing exception if n is above 16

            if (n > 16) {

                  throw new TooLargeArgumentException(

                              "Error: Too large value for n (" + n + ")");

            }

            int fac = 1;

            for (int i = n; i > 0; i--)

                  fac *= i;

            return fac;

      }

}

//Factorials.java

import java.util.Scanner;

public class Factorials {

      public static void main(String[] args) {

            String keepGoing = "y";

            Scanner scan = new Scanner(System.in);

            while (keepGoing.equalsIgnoreCase("y")) {

                  System.out.print("Enter an integer: ");

                  int val = scan.nextInt();

                  // putting the code to find and display factorial inside try catch

                  // block

                  try {

                        System.out.println("Factorial(" + val + ") = "

                                    + MathUtils.factorial(val));

                  } catch (NegativeArgumentException e) {

                        //NegativeArgumentException has occurred

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

                  } catch (TooLargeArgumentException e) {

                        //TooLargeArgumentException has occurred

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

                  }

                  System.out.print("Another factorial? (y/n) ");

                  keepGoing = scan.next();

            }

      }

}

/*OUTPUT*/

Enter an integer: 5

Factorial(5) = 120

Another factorial? (y/n) y

Enter an integer: -2

Error: Negative value for n (-2)

Another factorial? (y/n) y

Enter an integer: 12

Factorial(12) = 479001600

Another factorial? (y/n) y

Enter an integer: 16

Factorial(16) = 2004189184

Another factorial? (y/n) y

Enter an integer: 17

Error: Too large value for n (17)

Another factorial? (y/n) n

Add a comment
Know the answer?
Add Answer to:
File Factorials.java contains a program that calls the factorial method of the MathUtils class to compute...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Use the Summation recursive program you did in the class to also work with minus integers....

    Use the Summation recursive program you did in the class to also work with minus integers. For example, the sum of -3 will be -6 which is (-3)+(-2)+(-1)+0. USE THIS CODE package project5; import java.util.Scanner; public class SingleRecursion { /** Main method */ public static long sum(int n) {    if (n<0) throw    new IllegalArgumentException ("Can't calculate factorial of negative");    if (n==1)        return 1;    else if (n==0)        return 1;    else       ...

  • I just need to add comment for the code blow. Pleas add comment for each method...

    I just need to add comment for the code blow. Pleas add comment for each method and class if comments left out. package exercise01; /*************************************************************************** * <p> This program demonstrates the technique of recursion and includes * recursive methods that are defined for a variety of mathematical * functions. *    * <br>A recursive method is one that directly or indirectly calls itself * and must include: * <br>(1) end case: stopping condition * which terminates/ends recursion * <br>(2) reduction:...

  • given the following two classes Within a file named Rational.java, define a public class named Rational...

    given the following two classes Within a file named Rational.java, define a public class named Rational such that … the Rational class has two private instance variables, numerator and denominator, both of type int the Rational class defines two public accessor methods, numerator() and denominator() the Rational class defines a constructor that has one String parameter a throws clause indicates that this constructor could potentially throw a MalformedRationalException this constructor throws a MalformedRationalException in the following circumstances … When the...

  • Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program...

    Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program named GetIDAndAge that continually prompts the user for an ID number and an age until a terminal 0 is entered for both. If the ID and age are both valid, display the message ID and Age OK. Throw a DataEntryException if the ID is not in the range of valid ID numbers (0 through 999), or if the age is not in the range...

  • Assume that you have a String "name" attribute in a Java class definition.  Write a public method...

    Assume that you have a String "name" attribute in a Java class definition.  Write a public method to return this "name" attribute. public String getName() { return name;         } 1.) Write a statement that throws an IllegalArgumentException with the error message “Argument cannot be negative”.​ 2.) The method getValueFromFile is public and returns an int. It accepts no arguments. The method is capable of throwing an IOException and a FileNotFoundException. Write the header for this method.

  • Change the factorial method to return a BigInteger. You can leave the parameter value alone (ie,...

    Change the factorial method to return a BigInteger. You can leave the parameter value alone (ie, the parameter will remain an integer). You'll need to modify the method to use BigInteger objects and instance methods. Hint: remember that you can easily form Strings from numerical values by concatenating the numerical value with the empty String "". For Example: String s = 5 + ""; •What happens when you rerun your loop in main? Do you get the correct answers? import...

  • PrintArray vi Create a class called PrintArray. This is the class that contains the main method....

    PrintArray vi Create a class called PrintArray. This is the class that contains the main method. Your program must print each of the elements of the array of ints called aa on a separate line (see examples). The method getArray (included in the starter code) reads integers from input and returns them in an array of ints. Use the following starter code: //for this program Arrays.toString(array) is forbidden import java.util.Scanner; public class PrintArray { static Scanner in = new Scanner(System.in);...

  • 4.25 Lab9d: Factorials This program will output the factorial of numbers 1 through 10. Recall that...

    4.25 Lab9d: Factorials This program will output the factorial of numbers 1 through 10. Recall that 10! = 10 * 9 * 8 * 7 * … * 2 * 1. Calculating the factorial will require two loops. The outer loop will iterate from the number 1 up to and including the number n. n will be based on a number the user entered (an int value). The inner loop will calculate the factorial of the number the first loop...

  • 1. Employees and overriding a class method The Java program (check below) utilizes a superclass named...

    1. Employees and overriding a class method The Java program (check below) utilizes a superclass named EmployeePerson (check below) and two derived classes, EmployeeManager (check below) and EmployeeStaff (check below), each of which extends the EmployeePerson class. The main program creates objects of type EmployeeManager and EmployeeStaff and prints those objects. Run the program, which prints manager data only using the EmployeePerson class' printInfo method. Modify the EmployeeStaff class to override the EmployeePerson class' printInfo method and print all the...

  • Copy the program AmusementRide.java to your computer and add your own class that extends class AmusementRide....

    Copy the program AmusementRide.java to your computer and add your own class that extends class AmusementRide. Note: AmusementRide.java contains two classes (class FerrisWheel and class RollerCoaster) that provide examples for the class you must create. Your class must include the following. Implementations for all of the abstract methods defined in abstract class AmusementRide. At least one static class variable and at least one instance variable that are not defined in abstract class AmusementRide. Override the inherited repair() method following the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT