Factorial Java Program... Help?
So I'm doing a factorial java program (if thats actually one..I'm not sure, I just started Java II) and it keeps showing errors. Can anyone help me out here? And doesn't anyone know how to do factorial iterative? Haha, I'm such a noob at Java
import javax.swing.JOptionPane;
public class factorialMenu
{
public static void main (String args[])
{
String numbers[] = new String[4];
boolean stop = false;
String menu = "1. Recurson n\\n\\ 2. Iterative n\\n\\3. Exit";
String choice;
do
{
choice = JOptionPane.showInputDialog (menu + "n\\n\\ Enter menu choice number:");
if(choice.equals("1"))
recursion(numbers);
if(choice.equals("2"))
iterative(numbers);
else if(choice.equals("3"))
stop=true;
}
while(!stop);
}
public static void recursion(int n)
{
if ((n==0) || (n==1))
return 1;
else
return (n * fact(n-1));
}
}
Comments
As pointed out, when you changed the name of your "fact" method to "recursion," you forgot to change the name in your recursive call.
But a bigger problem is that you have declared the function with a return type of "void." It should return an integer type. Since factorials tend to be large numbers, you might consider returning a "long" type, and using the same type as the parameter.
Also, if the function is called with a negative parameter, the loop never terminates. So you may wish to test for this. (The following example returns a value of "1" for negative input, which may not be the behavior you desire.)
public static long recursion(long n)
{
if (n <= 1)
return 1;
else
return (n * recursion(n-1));
}
--
The iterative method simply uses a loop:
public static long iterative(int n)
{
long factorial = 1;
for(int i = 1; i <= n; i++)
factorial *= i;
return factorial;
}
Good luck!
It would help if you posted what the error message is that you get when you try to compile. Some of the things that I see that could be causing the error message is that you declare a double variable called integer but you don't use it, your implicitly cast an int to a double when you initialize fact, and you check to see if Fact == 0 which is a double checking on an int. These are just some possible causes but I won't know for sure until I can see what the error message is.
Your recursive method calls a method that doesn't exist. What is fact();? You don't have that in there. It should be calling itself and passing the n-1 parameter.