# Help with getting user input for my factorial method

Printable View

• April 4th, 2011, 09:29 AM
u-will-neva-no
Help with getting user input for my factorial method
Hello everyone! So here is my issue, I am using a while loop for a method to calculate the factorial of a number entered by the user. The while loop works correctly if have it inside my main (and class) but when I try to make a static method, I cant get user input. The reason why I am moving under my main is because i will eventually use a for loop to sum each iteration and i cant do that when it is together (at least i cant find a way). Ok here is my code...

Code Java:

``` import java.util.Scanner;   public class whileLoopFac { public static void main(String args[]) { Scanner input = new Scanner (System.in); System.out.println("Please enter a number the number of iterations: "); int n= input.nextInt(); //store the number that user inputs int callingMethod = Factorials(n);//calling Factorials method   /* for(int i=0; i<value; i++)//go through while loop as many times as iterated {       }//end loop   */ System.out.println("The factorial is: " + callingMethod );     }//end main   public static int Factorials(int k) {   int total = 1; //int input = n;//i want this to be user input HERE IS THE PROBLEM!! while(n > 0) { total *= n; n--; //decrement number entered by user     } return total; } //end SumFactorials   }//ends class```
When I compile, it is unable to know what n is (which has been defined in the main method) I have tried to move that into my static method but had no luck... Thankyou!
• April 4th, 2011, 12:41 PM
copeg
Re: Help with getting user input for my factorial method
See Variables (The Java™ Tutorials > Learning the Java Language > Language Basics)
The variable n is out of scope outside the main method, so you cannot reference it from another method. That being said it's value is passed to the factorial method as the parameter name k, so a) use k or b) change the parameter name to n
• April 4th, 2011, 01:24 PM
u-will-neva-no
Re: Help with getting user input for my factorial method
That worked perfectly lol. Thankyou!