2012-04-27 33 views

回答

5

您需要了解有關variable scope(以及鏈接至Java Tutorialanother 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 
    } 
} 
相關問題