In: Computer Science
In mathematics, the notation n! represents the factorial of the nonnegative integer n. The factorial of n is the product of non-negative numbers from 1 to n.
Design a program that asks the user to enter a nonnegative integer and then displays the factorial of that number.
Module main. Asks the user to enter a non-negative integer. A loop is used to require user input until a nonnegative number is entered. Once a nonnegative number is entered, the integer is passed to Module factorial.
Module factorial. Accepts a non-negative integer from Module main and uses a loop to calculate the factorial of that number. The number resulting from each step of the calculation will be written to an output file products.dat. The following numbers would be written to the output file for 7!
42
210
840
2520
5040
Module readFactorial. Changes the status of products.dat to an input file. Reads and displays all numbers in the file. The final number should be labeled as the solution to the problem.
Expected Input/Output
Your results should be similar to the following:
Please enter a non-negative integer: -5
The number must be non-negative.
Please enter a non-negative integer: 0
The number must be non-negative.
Please enter a non-negative integer. 7
Following are intermediary calculations for 7 factorial:
42
210
840
2520
5040
7 factorial is 5040.
Please use java to generate the program. And must have these modules and use these guidelines!!!
Program Code to Copy
import java.io.*; import java.util.Scanner; class Main{ static void module(int n) throws IOException { int ans = n; //Writer to write to file BufferedWriter bw = new BufferedWriter(new FileWriter("products.dat")); for(int i=n-1;i>1;i--){ //Multiply with current number ans = ans*i; //Write to file bw.write(ans+"\n"); } //Flush and close file bw.flush(); bw.close(); } public static void main(String[] args) throws IOException { //Prompt for non negative number System.out.print("Enter a non negative number: "); Scanner obj = new Scanner(System.in); int n = obj.nextInt(); //Call module and store the info in file module(n); //Read the file BufferedReader br = new BufferedReader(new FileReader("products.dat")); String s; String finalAns=""; //Read all lines while((s=br.readLine())!=null){ System.out.println(s); finalAns = s; } //Write factorial to output System.out.println(n+" factorial is "+finalAns); br.close(); } }
Screenshot:
Output:.