Question

In: Computer Science

PLEASE READ AND DO NOT COPY AND PASTE THE ANSWER. PROGRAM NEEDS TO INCLUDE MYEXCEPTION.JAVA File...

PLEASE READ AND DO NOT COPY AND PASTE THE ANSWER. PROGRAM NEEDS TO INCLUDE MYEXCEPTION.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.

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

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

Solutions

Expert Solution

import java.util.Scanner; 



// MathUtils.java

class MathUtils

{

// Return Factorial of User Input Value of n

public static int factorial(int n) throws myException

{

if(n<0) throw new myException("You have provided negative number ");

else if(n>16) throw new myException("Given input's factorial will cause the integer overflow");

else {

int fac = 1;

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

fac *= i;

return fac;

}

}

}

 

@SuppressWarnings("serial")



//myException Class

//Custom Exception class



 

class myException extends Exception{

myException(String s){  

  super(s);  

}  

}

 


// Factorial_Exception.java
// Reads integers from the user and prints the factorial of each.



public class Factorial_Exception

{

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();

//placing try catch block here as it must not stop flow of the program

try {

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

+ MathUtils.factorial(val));

}

catch(myException s) {

System.out.println("Following exception occured: "+s.getMessage()+"\n");

}

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

keepGoing = scan.next();

}

}

}

Output Screenshot:

Please upvote if you find this to be helpful


Related Solutions

IN YOUR OWN WORDS-PEASE DO NOT COPY AND PASTE ) PLEASE READ-->DO NOT ANSWER QUESTIONS__> Please...
IN YOUR OWN WORDS-PEASE DO NOT COPY AND PASTE ) PLEASE READ-->DO NOT ANSWER QUESTIONS__> Please determine in each questions wether it is biased and which is unbiased for both A & B. How their examples do or do not create a bias. 1) A) Do you think obesity is the cause of cardiovascular diseases (CVD)? B) Why people don’t lose weight to decrease risk factors for cardiovascular diseases (CVD)? 2 A) Do you think High Blood Pressure is caused...
In context of Australia ; Please answer in detail and do not copy paste for any...
In context of Australia ; Please answer in detail and do not copy paste for any other source 1)A client has receipts for $50.00 from donations provided to door to door charity collectors. Can the client claim a tax deduction for this amount? Why? 40–50 words 2) A client wants to claim $300 for work-related expenses and says they might not have spent that amount but because it does not need to be substantiated they will still make the claim....
There are two answer already posted up on this website please do not copy and paste...
There are two answer already posted up on this website please do not copy and paste from one of those I can not use those, Please help I have posted this before but all I get is a copy paste, Please no less then 3 paragraphs the more the better THank you for your help and I will rate well. Select a familiar or local Common Resource or Public Good (see text for examples to consider). Assess the existence of...
Please do not copy and paste an old question's asnwer. Please provide a new answer. Write...
Please do not copy and paste an old question's asnwer. Please provide a new answer. Write a paper (1,500-1,750 words) in which you address the following based on the information provided in the "West Coast Transit Case Study" resource.Use at least two sources as references for this assignment. APA Style. Define the three criteria for evaluating effective team/group work (as stated in the reading this week) and analyze whether the "team" assembled by Bernie Hollis and Pete Denson is effective...
Please answer at least in 300 words. Please do NOT copy and paste from another source....
Please answer at least in 300 words. Please do NOT copy and paste from another source. Discuss the differences between the traditional HDI in comparison to the “new” (NHDI) formulation. In what ways do you think either one is a better measure of human development?
Answer the following questions at least in 200 words each. Please do NOT copy and paste...
Answer the following questions at least in 200 words each. Please do NOT copy and paste from another source (Looking for answers not plagiarism). Please include any sources which were used. 1- According to Socrates, what is the value of justice? Why should we go to the trouble of being just? Is this discussion of justice still relevant today? How it affects economics? 2- Socrates believed that the "ideal city" should be comprised of three classes. What are these classes,...
**** PLEASE DO NOT COPY AND PASTE FROM ANOTHER SOURCE BECAUSE THE ANSWER IS INCOMPLETE********* Introduction:...
**** PLEASE DO NOT COPY AND PASTE FROM ANOTHER SOURCE BECAUSE THE ANSWER IS INCOMPLETE********* Introduction: IN C PROGRAMMING For this assignment you will write an encoder and a decoder for a modified "book cipher." A book cipher uses a document or book as the cipher key, and the cipher itself uses numbers that reference the words within the text. For example, one of the Beale ciphers used an edition of The Declaration of Independence as the cipher key. The...
Please provide detailed answer for each category. Do not copy paste. The statement of Cash Flows...
Please provide detailed answer for each category. Do not copy paste. The statement of Cash Flows has three categories, Operating, Investing, and Financing. Write the importance of each category to a potential investor and why?
Answer the below question in your own words please do not copy and paste. 4. What...
Answer the below question in your own words please do not copy and paste. 4. What is an industry that is in the maturity phase of the life cycle? How intense is the competition? 5. What is an example of an industry in the decline stage? What strategies are the current firms following? 6. Can you think of a firm that has completed a successful (or unsuccessful) turnaround?
Please do not go to a website and copy and paste a bunch of stuff that...
Please do not go to a website and copy and paste a bunch of stuff that does not answer the question. *ICD 10 PCS* 1. Research and discuss the guidelines that apply to the coding of CABGs, Pacemaker insertions, and also to the Coding of a Debridement.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT