Ask Question, Ask an Expert

+61-413 786 465

info@mywordsolution.com

Ask Computer Engineering Expert

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. 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. 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. You could define your own exception class, but there is already an exception appropriate for this situation IllegalArgumentException, which extends RuntimeException. Modify your program as follows:

  • Modify the header of the factorial method to indicate that factorial can throw an IllegalArgumentException.
  • Modify the body of factorial to check the value of the argument and, if it is negative, throw an IllegalArgumentException. Note that what you pass to throw is actually an instance of the IllegalArgumentException class, and that the constructor takes a String parameter. Use this parameter to be specific about what the problem is.
  • 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.
  • 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.

2.     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 an IllegalArgumentException - 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 an IllegalArgumentException 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;

}

}

Computer Engineering, Engineering

  • Category:- Computer Engineering
  • Reference No.:- M92544416
  • Price:- $25

Priced at Now at $25, Verified Solution

Have any Question?


Related Questions in Computer Engineering

A simple substitution cipher can be created by shifting a

A simple substitution cipher can be created by shifting a letter n positions in alphabetic order. For example, if the possible characters are the list [A...Za...z], a shift of three would translate A to D and Z to c. The ...

A firm faces the following inverse demand curvep

A firm faces the following inverse demand curve P= 54-0.5Q Where P is the price of output and Q is the number of outputs sold per hour. This firm is the only employer in town and faces an hourly supply of labor given by: ...

At a certain temperature 03811 mol of n2 and 1721 mol of h2

At a certain temperature, 0.3811 mol of N2 and 1.721 mol of H2 are placed in a 3.00-L container. N 2 (g)+3H 2 (g) ----->2NH 3 (g) At equilibrium, .1601 mol of N2 is present. Calculate the equilibrium constant, Kc.

Video and disruption report assignmentoverviewfor this

Video and Disruption Report Assignment Overview For this assessment task, you will create a two-minute video and written proposal about the impact of a particular technology on an industry or field. The purpose of this a ...

Question for this assignment you will continue your

Question: For this Assignment, you will continue your practice as a critical consumer of research. You will critically evaluate a scholarly article related to one-way ANOVA testing. To prepare for this Assignment: • Use ...

Suppose that 75 of all trucks undergoing a brake inspection

Suppose that 75% of all trucks undergoing a brake inspection at a certain inspection facility pass the inspection. Consider groups of 15 trucks and let X be the number of trucks in a group that have passed the inspection ...

Select one of the methods that makes the most sense to you

Select one of the methods that makes the most sense to you, and list the steps in detail. Imagine that you're tutoring another student in how to calculate subnets, and be sure to include enough detail that the steps woul ...

Diacussion 1 how would one distinguish between an

Diacussion: 1) How would one distinguish between an organizational weekness and threat to the organization? The response must be typed, single spaced, must be in times new roman font (size 12) and must follow the APA for ...

A chemistry student needsnbsp600 mlnbspof carbon

A chemistry student needs 60.0 mL of carbon tetrachloride for an experiment. By consulting the  CRC Handbook of Chemistry and Physics , the student discovers that the density of carbon tetrachloride is 1.59 g.cm^-3. Calc ...

Answer the following questions whats the synchronous

Answer the following Questions : What's the synchronous distribution ? What are the guidelines for menu layout or list them?

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As