java将一个值常量从一个方法保存到一个重载方法
我目前正在学习java入门课程,我在这里被难住了
我创建了一个rollDice()
方法,它使用Math.random
生成存储在变量d1
和d2
中的2int
类型的值。如果该和的值之和等于4、6、8、9、10或11,则调用重载方法^{
我的问题是,我似乎无法保持原始valuePoint
不变,因为它最初被建立为valuePoint = sum
。所以每次我在第二种方法中掷骰子,valuePoint
再次变为相等的和。我希望我能很好地解释我的问题
public void play(){
rollDice();
sum = d1 + d2;
if(sum == 2 || sum == 3 || sum == 5) {
status = "You Lose.";
valuePoint = 0;
System.out.println(status);
}
else if(sum == 7 || sum == 11) {
status = "You Win!";
valuePoint = 0;
System.out.println(status);
}
else {
status = "You established the value point ";
valuePoint = sum;
System.out.println(status + valuePoint);
}
if(valuePoint == sum)
play(d1,d2);
} // end of method
public void play(int d1, int d2){
final int vp = valuePoint;
sum = 0;
start = true;
while (true) {
System.out.println("Roll again..");
rollDice();
sum = d1 + d2;
if (sum == vp) {
status = "You Win!";
System.out.println(status);
start = false;
break;
}
else if (sum == 7) {
status = "You Lose.";
System.out.println(status);
start = false;
break;
}
} // end of while
} // end of method
这是我的输出样本
You rolled 1 + 5 = 6
You established the value point 6
Roll again..
You rolled 2 + 6 = 8
You Win!
请注意,第二卷没有到达valuepoint
,但它仍然是一个胜利,因为valuePoint
已更改为新的总和
问题中也给出了属性和操作,所以我必须遵循这个API才能获得满分。我添加到属性中的唯一变量是final int vp
,试图在第一次建立时保持darn valuePoint
不变,但这不起作用
# 1 楼答案
这个问题实际上与范围有关。在方法
play(int d1, int d2)
中,当您在sum = d1 + d2;
行中引用d1
和d2
时,实际上是指函数的参数,而不是实例变量,因为参数具有更“局部范围”。因此,你永远不会用两个新值来更新一个和。您可以通过更改参数的名称,使其与实例变量不同,或者将实例变量引用为this.d1
和this.d2
,来解决这个问题