Question
* This is for CS 101 Java class. I can only use while loops. I cannot use for, do-while or any other repetition method.* Write
* This is for CS 101 Java class. I can only use "while" loops. I cannot use "for", "do-while" or any other repetition method.*
Write a program that calculates the factorial of a given number. First, it asks for an integer number x between [0 13] and calculates its factorial. The program should run until users input is an invalid number (outside of interval).
A sample run is shown below:
Please enter a number [0-13]: 0
0! = 1
Please enter a number [0-13]: 5
5! = 120
Please enter a number [0-13]: 2
2! = 2
Please enter a number [0-13]: -1
Goodbye!
This is my code but after the calculation of first factorial it does not work correctly.
import java.util.Scanner; public class Lab04a { public static void main(String[] args) { Scanner in = new Scanner(System.in); //Constants //Variables int i; int number; long factorial; //Initialize the variables System.out.println("Please enter a number [0-13]: "); number = in.nextInt(); i = 1; factorial = 1; //Program code while (0 <= number && number <= 13) { while (number > i) { factorial = factorial * number; number--; } System.out.println(number + "! = " + factorial); System.out.println("Please enter a number [0-13]: "); number = in.nextInt(); } System.out.println("Invalid number."); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started