public static int Factorial(int num) {
int factorial = 1;
int num = Integer.parseInt(txtFactorial.getText());
for (int i = 1; i <= num; i++) {
factorial = factorial * 1;
}
return factorial;
}
The code above is a code I'm trying to put in a subroutine to find the factorial of a number entered by a user and display it in a JLabel
. The problem is that it is showing an error with the int num = Integer.parseInt(txtFactorial.getText());
code. This piece of code gets the entry of the user and stores it into the variable num for it to be later used to find the factorial.
You should change your calculation.
public static int Factorial(int num)
{
int factorial = 1;
// delete this line int num = Integer.parseInt(txtFactorial.getText());
for (int i = 1; i<=num; i++)
{
factorial = factorial * i;
}
return factorial;
}
And use the function like this:
ResultLabel.setText(string.valueOf(Factorial(Integer.parseInt(txtFactorial.getText()))));