Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program in java that does the following: 1. It prompts the user for an i

ID: 673199 • Letter: W

Question

Write a program in java that does the following:

1. It prompts the user for an integer

2. It calculates the factorial of that integer in another method (public double factorial(int n)). Observe that the factorial of an integer n is given by:

   factorial(n) = n (n – 1)(n – 2)… 3. 2. 1

For example

factorial(4) = 4.3.2.1 = 24

By definition,

   factorial(0) = 1.

3. The resulting factorial is printed in the main method:

A sample output session is:

Enter an integer: 5

The factorial of 5 is 120.

4. Several exceptions could be thrown in this process.

(a) if the user enters a non-integer (for example 3.5)

(b) if the user enters a negative integer (factorials of negative integers are not defined)

(c) if the user enters an integer whose factorial is too large to fit in the range int.

   (Typically java’s primitive type int cannot calculate factorial(14) or higher correctly).

5. Use java’s built-in exceptions and/or user defined exceptions to catch an exception and print an appropriate message for each one of the above cases separately. Make sure the program repeatedly asks for user input until the user enters a valid input. The program then prints the factorial of the input.

A sample output session is:

Enter an integer: 3.5

Exception: You entered a non-integer

Enter an integer: -3

Exception: You entered a negative integer

Enter an integer: 20

Exception: factorial(20) is too large for int data type

Enter an integer: 7

The factorial of 7 is 5040

Process Completed.

Explanation / Answer

class fac
{

public static void main (String[ ] args)
{
System.out.println("Enter the number : ");

java.util.scanner scn=new java.util.scanner(System.in);
int a = scanner.nextInt();
double fact= 1;
  
System.out.println("Factorial of " +a+ ":");
  
{

if ( i< 0 )
System.out.println("you entered a negative number");

else if(number is interger)

{

System.out.println("you entered a non interger");

}

else if(i<20)

{

System.out.println("factorial(20) is too large for int data type");

}

else if(i>0)

{

System.out.println("you entered a negative number");

}

else
{
for (int i= 1; i<=a; i++)

   fact=fact*i;

}
System.out.println(fact);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote