我不确定如何使用
Scanner stdin = new Scanner(System.in); //Keyboard input
Run Code Online (Sandbox Code Playgroud)
我在main()中声明了包含它的类的其他方法.我得到"stdin无法解决".
您需要了解变量范围(这里是Java Tutorial的链接,另一个是变量范围).
要在其他方法中使用该变量,您需要将引用传递给其他方法.
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
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将扫描程序声明为静态字段:
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1860 次 |
| 最近记录: |