0

私は人のリストを持つクラスを持っています。クラス PersonBeholder (ノルウェー語で PersonContainer を意味します) を作成しました。また、Person クラスと、Person 間の関係を作成するメイン クラスもあります。メイン クラス以外の人物の一般的なリストを参照しようとすると、問題が発生します。

class TestPersoner{
public static void main (String [ ] args){

   **PersonBeholder pl = new PersonBeholder();**

    Person Emil = new Person("Emil");
    Person Nils = new Person("Nils");

    pl.settInnPerson(Emil);        //this populates the list
    pl.settInnPerson(Nils);

    }

}

メインの外部から PersonBeholder pl を参照しようとすると、問題が発生します。

public void blirVennMed(Person p){
if(!pl.erIbeholder(p.hentNavn())) System.out.print("This is not going to work");
//this does check if there is someone in the container named p.hentNavn()
}

出力

TestPersoner.java:26: error: cannot find symbol
if(!pl.erIbeholder(p.hentNavn())) System.out.print("This is not going to work");
    ^
  symbol:   variable pl
  location: class Person
1 error

今、私はこのようにしました:

class TestPersoner{
public static PersonBeholder pl = new PersonBeholder();
public static void main (String [ ] args){  

    Person Emil = new Person("Emil");
    Person Nils = new Person("Nils");

    pl.settInnPerson(Emil);        //this populates the list
    pl.settInnPerson(Nils);

    }

}

そして、それはまだ機能しません。

4

2 に答える 2

1

オブジェクトのスコープは main-method にあります。それ以外で使用する場合は、クラス TestPersoner のメンバーとして宣言するか、引数としてメソッドに渡します。

于 2013-02-15T11:10:40.603 に答える
0

Local variablesメソッドのスコープにのみ限定されます。それらを定義したメソッドの外でそれらを使用することはできません。明示的に返さない限り、メソッドの完了後にGC'Dを取得するだけです。

于 2013-02-15T11:10:04.153 に答える