在Class2中使用Class1的方法值,它扩展了Class1

时间:2014-10-27 02:18:56

标签: java

我是Java新手。通过将PairOfDice类的总和值传递到DiceRollerapp类来进行堆叠,其中,根据总和,显示不同的消息。无论如何,sumDiceRollerapp中都为0。非常感谢任何帮助。

public class PairOfDice extends Die {

    private int sum;
    private int d1,d2;

    public PairOfDice() {
        super();
          }
public PairOfDice(int sum){
this.sum=sum;
}


    public int getValue1() {
        d1=super.getValue();
        return d1;
    }

    public int getValue2() {
        d2=super.getValue();
        return d2;
    }



    public int getSum(){
       sum=d1+d2;
    return sum;

    }

    public void setSum(int sum){
    this.sum=sum;
    } 

}

public class DiceRollerapp extends PairOfDice{

private int total;

public DiceRollerapp() {
    super();
}
public DiceRollerapp(int sum) {
    super(sum);
}  



public String getMessage() {

   total=super.getSum();

    if (total == 7) {
        System.out.println("CRAPS!");
    } else if (total == 12) {
        System.out.println("BOX CARS!");
    } else if (total == 2) {
        System.out.println("SNAKE EYES!");
    } else {
        System.out.println("");
    }
    return "";
}

}

1 个答案:

答案 0 :(得分:0)

问题在于

public int getSum(){
  sum=d1+d2;
  return sum;
}

始终根据d1d2重新计算总和。这意味着您必须在致电getSum()之前设置它们。

public String getMessage() {
  super.getValue1();    // <-- sets d1.
  super.getValue2();    // <-- sets d2
  total=super.getSum(); // <-- adds d1 and d2.
  if (total == 7) {
    System.out.println("CRAPS!");
  } else if (total == 12) {
    System.out.println("BOX CARS!");
  } else if (total == 2) {
    System.out.println("SNAKE EYES!");
  } else {
    System.out.println("");
  }
  return "";
}