2012-04-27 3 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 
    } 
} 
関連する問題