I am new to Java. I am trying to find the factorial of a number using Scanner. I am getting an error at p as p cannot be resolved to a variable. What does it mean?
import java.util.Scanner;
public class fact {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner object = new Scanner(System.in);
System.out.println("enter a number:\n");
int i = object.nextInt();
int result = 1;
for (p = 1; p <= i; p++) {
result = result * 1;
System.out.println("factorial of a number is:result");
}
}
}
It means you haven't defined a variable p (and yet you try to initialize it to 1 in your for loop). Change
for(p=1;p<=i;p++)
to
for(int p=1;p<=i;p++)
You have several errors here:
The first (and most important) is that you never define p. As the other answers say, define it either beforehand (int p;) or in the loop.
The second is that you're not actually calculating the factorial, which is an additional problem. But solve problem 1 first as it is a compiler error.
The third is that you're not actually printing the result. You'd need to do System.out.println("The result was: " + result).
Also, you may not want the print statement to be inside the loop...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With