我是Java新手。通过将PairOfDice
类的总和值传递到DiceRollerapp
类来进行堆叠,其中,根据总和,显示不同的消息。无论如何,sum
在DiceRollerapp
中都为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 "";
}
}
答案 0 :(得分:0)
问题在于
public int getSum(){
sum=d1+d2;
return sum;
}
始终根据d1
和d2
重新计算总和。这意味着您必须在致电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 "";
}