0

プログラムで別のクラスからプライベート変数を入力したい。

ミューテーターとアクセサーを使いたい。

NullPointerException のエラーが発生し続けます。私のコードの問題は何ですか?

public abstract class Inputs {
private String val;
private String typ;
public abstract void setVal(String val);
public abstract void setTyp(String typ);
public abstract String getVal();
public abstract String getTyp();
}

public DeckOfCards extends Inputs{
String val;
String typ;
static DeckOfCards kerds = new DeckOfCards();
    public void setVal(String val){
        this.val = val;
    }

    public void setTyp(String typ){
        this.typ = typ;
    }

    public String getVal(){
        return this.val;
    }

    public String getTyp(){
        return this.typ;
    }
    public static void main(String args[]){
       System.out.print("Value: ");
       kerds.setVal(kerds.val);
       if(kerds.val.equals("A"){
          System.out.print("Type: ");
          kerds.setTyp(kerds.typ);
       }
    }
}
4

2 に答える 2

1

Here is your problem kerds.setVal(kerds.val); kerds is not created yet when main runs.

  • You need to initialize the instance of DeckOfCards before using it.
  • Only attempt to retrieve values after they are set. Else the attempt to retrieve a value that isn't yet set will throw a NullPointerException (Just as Rehman has pointed out)

Here is an example of proper usage:

     public static void main(String args[]){
        DeckOfCards kerds = new DeckOfCards();
        kerds.setVal("A");
        kerds.setTyp("TYPE_A");

        System.out.println("Displaying values of kerds");
        System.out.println("kerds value : " + kerds.getVal());
        System.out.println("kerds type : " + kerds.getTyp());
        }
于 2015-10-02T08:24:43.787 に答える
0

kerds.setVal(kerds.val)null 値を設定しています。その時点で kerds.val の値はまだ設定されていません。基本的に、あなたのコードは意味がありません。まだ設定されていない同じプロパティの値を持つプロパティを設定しています。

于 2015-10-02T08:33:50.977 に答える