Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"cannot be resolved to a variable" in for loop

Tags:

java

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");
        }

    }

}
like image 295
aishwaryat Avatar asked Jul 25 '26 10:07

aishwaryat


2 Answers

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++)
like image 106
Elliott Frisch Avatar answered Jul 28 '26 00:07

Elliott Frisch


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...

like image 33
hyper-neutrino Avatar answered Jul 28 '26 00:07

hyper-neutrino