nnn
nnn

Reputation: 1037

How to use keyboard input declared in main() in other methods of the class containing it?

I'm not sure how to use

Scanner stdin = new Scanner(System.in);  //Keyboard input

which I declare in main() in other methods of the class containg it. I get "stdin cannot be resolved".

Upvotes: 0

Views: 1927

Answers (1)

Greg Kopff
Greg Kopff

Reputation: 16615

You need to learn about variable scope (and here's a link to the Java Tutorial, and another on variable scope).

In order to use that variable in other methods, you need to pass a reference to your other methods.

public static void main(String[] args)
{
  Scanner stdin = new Scanner(System.in);  // define a local variable ...
  foo(stdin);                              // ... and pass it to the method
}

private static void foo(Scanner stdin)
{
  String s = stdin.next();                 // use the method parameter
}

Alternatively, you could declare the scanner as a static field:

public class TheExample
{
  private static Scanner stdin;

  public static void main(String[] args)
  {
    stdin = new Scanner(System.in);       // assign the static field ...
    foo();                                // ... then just invoke foo without parameters
  }

  private static void foo()
  {
    String s = stdin.next();              // use the static field
  }
}

Upvotes: 5

Related Questions