I am supposed to create a program that asks the user for a number and takes the factorial of that number then asks if they want to do another factorial (Y,N).
It is supposed to work like this:
My output is like:
4! = 1 regardless of whether I enter Y or N.
Here's my code:
import java.util.Scanner;
public class factorial
{
public static void main ( String [] args )
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number you want to take the factorial of: ");
int num = input.nextInt();
int fact = 1;
System.out.printf("%d! = %d\n ", num, fact, Factorial(num, fact));
}
public static int Factorial(int num, int fact)
{
Scanner input = new Scanner(System.in);
char foo;
System.out.print("Do another factorial (Y,N)?");
foo = input.next().charAt(0);
for (int i = 1; i >= num; i++)
{
fact *= i;
if (foo == 'Y')
{
System.out.print("Do another factorial (Y,N)?");
foo = input.next().charAt(0);
continue;
}
else
{
break;
}
}
return fact;
}
}
After the change:
import java.util.Scanner;
public class factorial
{
public static void main ( String [] args )
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number you want to take the factorial of: ");
int num = input.nextInt();
int fact = 1;
System.out.printf("%d! = %d\n ", num, Factorial(num, fact));
System.out.print("Do another factorial (Y,N)? ");
char foo = input.next().charAt(0);
while (foo != 'N')
{
System.out.print("Do another factorial (Y,N)? ");
foo = input.next().charAt(0);
System.out.print("Enter a number you want to take the factorial of: ");
num = input.nextInt();
System.out.printf("%d! = %d\n", num, Factorial(num, fact));
}
}
public static int Factorial(int num, int fact)
{
for (int i = 1; i <= num; i++)
{
fact *= i;
}
return fact;
}
}
Output still has some problems:
You compute factorial, but you never print it:
System.out.printf("%d! = %d\n ", num, fact, Factorial(num, fact));
should be
System.out.printf("%d! = %d\n ", num, Factorial(num, fact));
Moreover, your Factorial
function does not make use of the fact
parameter, so you should remove it, and declare a local variable inside the function.
Finally, asking for the "do you want another factorial" should be done at the top level, not inside the Factorial
function. Your code does not use the character that the user inputs, too: you'll need a loop that checks user's input, and continues while Y
is entered.