Question

In: Computer Science

Throwing Exceptions - JAVA File Factorials contains a program that calls the factorial method of theMathUtils...

Throwing Exceptions - JAVA

File Factorials contains a program that calls the factorial method of theMathUtils class to compute the factorials of integers entered by the user. Save these files to your directory and study the code in both, then compile and run Factorials to see how it works. Try several positive integers, then try a negative number. You should find that it works for small positive integers (values < 17), but that it returns a large negative value for larger integers and that it always returns 1 for negative integers.

  1. Create a custom exception class called myException. This class should take in one String parameter that can be passed to the super class inside the constructor
  2. Returning 1 as the factorial of any negative integer is not correct—mathematically, the factorial function is not defined for negative integers. To correct this, you could modify your factorial method to check if the argument is negative, but then what? The method must return a value, and even if it prints an error message, whatever value is returned could be misconstrued. Instead it should throw an exception indicating that something went wrong so it could not complete its calculation. Use your myException class to handle the situation. Modify your program as follows:
    1. Modify the header of the factorial method to indicate that factorial can throw a myException.
    2. Modify the body of factorial to check the value of the argument and, if it is negative, throw a myException. Note that what you pass to throw is actually an instance of the myException class, and that the constructor takes a String parameter. Use this parameter to be specific about what the problem is.
    3. Compile and run your Factorials program after making these changes. Now when you enter a negative number an exception will be thrown, terminating the program. The program ends because the exception is not caught, so it is thrown by the main method, causing a runtime error.
    4. Modify the main method in your Factorials class to catch the exception thrown by factorial and print an appropriate message, but then continue with the loop. Think carefully about where you will need to put the try and catch.
  3. Returning a negative number for values over 16 also is not correct. The problem is arithmetic overflow—the factorial is bigger than can be represented by an int. This can also be thought of as a myException — this factorial method is only defined for arguments up to 16. Modify your code in factorial to check for an argument over 16 as well as for a negative argument. You should throw a myException in either case, but pass different messages to the constructor so that the problem is clear.

Submit the following:

Modified MathUtils.java

Modified Factorials.java

myException.java

// ****************************************************************
// 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;
   }
}

// ****************************************************************
// 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.equals("y") || keepGoing.equals("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();
       }
   }
}

Solutions

Expert Solution

class GFG {

     

    // This function finds factorial of

    // large numbers and prints them

    static void factorial(int n)

    {

        int res[] = new int[500];

        // Initialize result

        res[0] = 1;

        int res_size = 1;

        // Apply simple factorial formula

        // n! = 1 * 2 * 3 * 4...*n

        for (int x = 2; x <= n; x++)

            res_size = multiply(x, res, res_size);

        System.out.println("Factorial of given number is ");

        for (int i = res_size - 1; i >= 0; i--)

            System.out.print(res[i]);

    }

     

    // This function multiplies x with the number

    // represented by res[]. res_size is size of res[] or

    // number of digits in the number represented by res[].

    // This function uses simple school mathematics for

    // multiplication. This function may value of res_size

    // and returns the new value of res_size

    static int multiply(int x, int res[], int res_size)

    {

        int carry = 0; // Initialize carry

        // One by one multiply n with individual

        // digits of res[]

        for (int i = 0; i < res_size; i++)

        {

            int prod = res[i] * x + carry;

            res[i] = prod % 10; // Store last digit of

                                // 'prod' in res[]

            carry = prod/10; // Put rest in carry

        }

        // Put carry in res and increase result size

        while (carry!=0)

        {

            res[res_size] = carry % 10;

            carry = carry / 10;

            res_size++;

        }

        return res_size;

    }

    // Driver program

    public static void main(String args[])

    {

        factorial(100);

    }

}

import java.util.Scanner;

import javax.swing.JOptionPane;

public class App {

public static void main(String[] args) {

    int value;

   //E.g. 4!=4*3*2*1

    Scanner keyboard=new Scanner(System.in);

    System.out.println("Enter a value for factorial");

    value=keyboard.nextInt();

    try{

    System.out.println(calculate(value));}catch(NumberFormatException e){

        System.out.println("invalid error. No negative numbers");

    }

}

private static int calculate(int value){

    if(value==1 || value==0){

        return 1;

    }

    return calculate(value-1)*value;

}

}

-----------------------------------------------------------------------------------------

import java.util.Scanner;

public class Factorials

{

public static void main(String[] args)

{

String keepGoing = "y";

Scanner scan = new Scanner(System.in);

while (keepGoing.equals("y") || keepGoing.equals("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();

}

}

}

public class MathUtils

{

public static int factorial(int n)

{

int fac = 1;

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

fac *= i;

return fac;

}

}


Related Solutions

java Factorials The factorial of n (written n!) is the product of the integers between 1...
java Factorials The factorial of n (written n!) is the product of the integers between 1 and n. Thus 4! = 1*2*3*4 = 24. By definition, 0! = 1. Factorial is not defined for negative numbers. Write a program that asks the user for a non-negative integer and computes and prints the factorial of that integer. You’ll need a while loop to do most of the work—this is a lot like computing a sum, but it’s a product instead. And...
1. Write a Java program and Submit only "one .java file" calledNumbers that calls the...
1. Write a Java program and Submit only "one .java file" called Numbers that calls the following methods and displays the returned value:o Write a method called cubeIt that accepts one integer parameter and returns the value raised to the third power as an integer.2. Write a method called randomInRange that accepts two integer parameters representing a range. The method returns a random integer in the specified range inclusive.o Write a method called larger that accepts two double parameters and...
Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in...
Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in English (dictionary), to find the number of misspelled words in a story file called Alcott-little-261.txt. Please note that the dictionary words are all lower-cased and there are no punctuation symbols or numbers. Hence it is important that you eliminate anything other than a-z and A-Z and then lower case story words for valid comparisons against the WordList file. When you read each line of...
Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in...
Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in English (dictionary), to find the number of misspelled words in a story file called Alcott-little-261.txt. Please note that the dictionary words are all lower-cased and there are no punctuation symbols or numbers. Hence it is important that you eliminate anything other than a-z and A-Z and then lower case story words for valid comparisons against the WordList file. When you read each line of...
A question about exceptions, the language is JAVA. The purpose is writing a program that reads...
A question about exceptions, the language is JAVA. The purpose is writing a program that reads a string from the keyboard and tests whether it contains a valid time. Display the time as described below if it is valid, otherwise display a message as described below. The input date should have the format hh:mm:ss (where hh = hour, mm = minutes and ss = seconds in a 24 hour clock , for example 23:47:55). Here are the input errors (Exceptions)...
There is a Java program that is missing one recursive function: public class Factorial { /*...
There is a Java program that is missing one recursive function: public class Factorial { /* / 1 when n is 0; * fact(n) = | * \ n*fact(n-1) otherwise */ public static int fact(int n) { return 0; } /* Factorial Test Framework * * Notice the odd expected value for fact(20). It is negative because * fact(20) should be 2432902008176640000, but the maximum int is only * 2147483647. What does Java do when integers run out of range?...
java programing project Implement a program that computes the Fibonacci of a specified number, the factorial...
java programing project Implement a program that computes the Fibonacci of a specified number, the factorial of a specified number, or estimates the value of 'e' using the specified number of iterations (of a Taylor series). Please feel free to use the Internet to find resources that explain how to estimate the value of 'e' using a Taylor series. In the case of no or invalid number of parameters, the program should show help instructions that looks like: --- Assign...
Write a program that asks the user for a file name. The file contains a series...
Write a program that asks the user for a file name. The file contains a series of scores(integers), each written on a separate line. The program should read the contents of the file into an array and then display the following content: 1) The scores in rows of 10 scores and in sorted in descending order. 2) The lowest score in the array 3) The highest score in the array 4) The total number of scores in the array 5)...
PLEASE DO NOT OVERRIDE ANY EXCEPTIONS TASK: You want to develop a Java program that will...
PLEASE DO NOT OVERRIDE ANY EXCEPTIONS TASK: You want to develop a Java program that will allow you to keep track of a set of employees. In reviewing your employee list, you notice that your employees fall into two categories: Salaried and Hourly. The following table shows the information that you keep in your employee list for each type of employee. Field Type Salaried Hourly id int Yes Yes name String Yes Yes title String Yes No position String No...
JAVA Write a program that demonstrates how various exceptions are caught with catch (Exception exception) This...
JAVA Write a program that demonstrates how various exceptions are caught with catch (Exception exception) This time, define classes ExceptionA (which inherits from class Exception) and ExceptionB (which inherits from class ExceptionA). In your program, create try blocks that throw exceptions of types ExceptionA, ExceptionB, NullPointerException and IOException. All exceptions should be caught with catch blocks specifying type Exception.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT