0
我不知道如何使用如何在包含它的類的其他方法中使用在main()中聲明的鍵盤輸入?
Scanner stdin = new Scanner(System.in); //Keyboard input
,我在main()在類方含它的其他方式申報。我得到「stdin無法解決」。
我不知道如何使用如何在包含它的類的其他方法中使用在main()中聲明的鍵盤輸入?
Scanner stdin = new Scanner(System.in); //Keyboard input
,我在main()在類方含它的其他方式申報。我得到「stdin無法解決」。
您需要了解有關variable scope(以及鏈接至Java Tutorial和another on variable scope)。
爲了在其他方法中使用該變量,您需要將引用傳遞給其他方法。
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
}
}