2

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

    }

}

4 Answers 4

6

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++)
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

You should define the variable p in your for loop like you have defined i variable like this:

for(int p = 1; p <= i; p++)

Comments

0

This code has lot of compilation errors. The following is the working code

import java.util.Scanner;

public class ScannerEx {

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    System.out.println("enter a number:\n");
    int number = scanner.nextInt();

    int result = 1;


    for(int p=1; p <=number ;p++)  {
        result= result*p;

    }
    System.out.println("Factorial of a number is " + result);
}

}

1 Comment

Starting a class with a capital letter is not a compilation error, just a convention taboo - you make it sound as if it's the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.