To reinforce the use of \"strange\" and for loops. Assignment Write a program th
ID: 3803803 • Letter: T
Question
To reinforce the use of "strange" and for loops. Assignment Write a program that reads in an integer greater than 1 in from the user. The program then computes and print out the factorial of the number read in. The factorial of a number is the product of all the natural numbers less than or equal to the number itself. That is the factorial of n is 1*2*3* ... (n - 2)*(n - 1)*n. Your program should stop if the user enters a negative number. Design You will probably want to make a class called Integer which has a single instance variable of class int. This class would also have an accessor method for the value and a method factorial, which will compute the factorial. This separates the input and output from the computation. Sample Output Enter a number: 5 The factorial of 5 is 120. Enter a number: 8 The factorial of 8 is 40320. Enter a number: 12 The factorial of 12 is 479001600. Enter a number: -1 Thank you and bye.Explanation / Answer
Integer.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author user
*/
import java.util.Scanner;
public class Integer {
//System.out.println("Do you want to look up another name in the directory? press y/n ");
public static void main(String[] args) {
//getnumbr();
Integer in=new Integer();
in.getnumbr();
}
public void getnumbr()
{
Scanner scanner = new Scanner(System.in);
char c;
do
{
System.out.print("Enter a number : ");
int n = scanner.nextInt();
if(n>1)
{
int result = factorial(n);
System.out.println("The factorial of " + n + " is " + result);
}
else
{
System.out.println("Thank You, Bye ");
System.exit(0);
}
System.out.println("Do you want to look up another name in the directory? press y/n ");
c=scanner.next().charAt(0);
if(c=='n')
{
System.exit(0);
}
}while(c!='n');
}
public int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
}
output:
run:
Enter a number : 4
The factorial of 4 is 24
Do you want to look up another name in the directory? press y/n
y
Enter a number : 8
The factorial of 8 is 40320
Do you want to look up another name in the directory? press y/n
y
Enter a number : 12
The factorial of 12 is 479001600
Do you want to look up another name in the directory? press y/n
y
Enter a number : -6
Thank You, Bye
BUILD SUCCESSFUL (total time: 34 seconds).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.