Program that calls the factorial method

Assignment Help Basic Computer Science
Reference no: EM131735730

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;

}

}

Reference no: EM131735730

Questions Cloud

Write 10 basic sql statements : Write 10 SQL statements against the STUDENT schema you created for practice lab 1. Your statements should run error-free and should be valid.
Determine crumpler budgeted net profit for the year : Determine Crumpler 's budgeted net profit for the year 2017. Calculate the following items for Crumpler: the projected safety margin in units for the year 2017
Arise in cellular manufacturing systems in practice : Discuss the design and planning problems that arise in Cellular Manufacturing Systems in practice.
What are the sources of these types of synergies : Explain the concepts of economy-of-scope and revenue-enhancement. What are the sources of these types of synergies?
Program that calls the factorial method : 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.
What types of scheduling decisions are management : What types of scheduling decisions are management likely to encounter in the following operations?
Would you recommend telecommuting for medex : Harry Davis just finished interviewing candidate to fill another medical billing specialist opening. Would you recommend telecommuting for MedEx?
How do the videos affect your perspective : How do the videos affect your perspective? Be thoughtful in your reflections, using the readings and the videos to help inform your writing.
Discuss the project well defined at the beginning : Was the project well defined at the beginning. Did team members work together cooperatively

Reviews

Write a Review

Basic Computer Science Questions & Answers

  Proposals coming from contractors who have unique skills

Proposals coming from contractors who have unique skills in providing goods and services are called:    a. best and final offers (BAFOs)    b. negotiated proposals

  Analyzing a security breach

Many types of systems are networked together, and the number of devices that are added to this network increases every year. You can set your home security alarm system using a smartphone app or use another mobile app to open your car door.

  What is the net present value of the investment

The investment will cost you $ 5,534 today. If the appropriate Cost of Capital is 11.0 %, what is the Net present Value of the investment?

  Disadvantages of alloying steel with silicon

State the advantages and disadvantages of alloying steel with silicon for use as magnetic materials in transformer and electric machines.

  Identify the primary key

Consider the following tables: CLIENT(CL_ID, CL_LNAME, CL_FNAME, CL_PHONE) PROJECT(PR_CODE, PR_DESCRIPTION, PR_PRICE, CL_ID)

  Safeguards against unreasonable searches and seizures

In this assignment, you need to work on the Fourth Amendment. Before starting on the assignment, make sure that you read about the Fourth Amendment and understand the nature/features of this amendment related to privacy. The Fourth Amendment safeguar..

  Colliding signals in a transmission cable

Suppose two nodes, A and B, are attached to opposite ends of an 800 m cable, and that they each have one frame of 1024 bits (including all headers and preambles) to send to each other.

  Displays the depreciation in value of a given item

Write a program in python 3.x that calculates and displays the depreciation in value of a given item. Given the following formulas:

  Write a deletion method for the redblack class

Design and implement a program that compares AVL trees and red-black trees to skip lists. Which data structure performs the best?

  Beginning of the month and after transaction

Compute the acid-test ratio as of the beginning of the month and after each transaction.

  Opinions regarding which operating system to use

IT professionals are often asked their opinions regarding which operating system to use.

  Multilayer infrastructure architecture

Using Visio, create a high level large enterprise data center design that follows the Cisco®multilayer infrastructure architecture. Please use the Insert/Comment or Insert/Text Box to provide a brief explanation of each component with detail.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd