Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在包含main()的类的其他方法中使用main()中声明的键盘输入?_Java_Input - Fatal编程技术网

Java 如何在包含main()的类的其他方法中使用main()中声明的键盘输入?

Java 如何在包含main()的类的其他方法中使用main()中声明的键盘输入?,java,input,Java,Input,我不知道怎么用 Scanner stdin = new Scanner(System.in); //Keyboard input 我在包含它的类的其他方法的main()中声明了它。我得到“stdin无法解析”。您需要了解(这里有一个指向和的链接) 为了在其他方法中使用该变量,需要传递对其他方法的引用 public static void main(String[] args) { Scanner stdin = new Scanner(System.in); // define a l

我不知道怎么用

Scanner stdin = new Scanner(System.in);  //Keyboard input
我在包含它的类的其他方法的main()中声明了它。我得到“stdin无法解析”。

您需要了解(这里有一个指向和的链接)

为了在其他方法中使用该变量,需要传递对其他方法的引用

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
}
或者,您可以将扫描仪声明为静态字段:

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
  }
}
您需要了解(这里是指向和的链接)

为了在其他方法中使用该变量,需要传递对其他方法的引用

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
}
或者,您可以将扫描仪声明为静态字段:

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