有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将一个值常量从一个方法保存到一个重载方法

我目前正在学习java入门课程,我在这里被难住了

我创建了一个rollDice()方法,它使用Math.random生成存储在变量d1d2中的2int类型的值。如果该和的值之和等于4、6、8、9、10或11,则调用重载方法^{,再次滚动骰子,直到和等于7(您输了)或和等于第一个方法中建立的原始^{

我的问题是,我似乎无法保持原始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) 个答案

  1. # 1 楼答案

    这个问题实际上与范围有关。在方法play(int d1, int d2)中,当您在sum = d1 + d2;行中引用d1d2时,实际上是指函数的参数,而不是实例变量,因为参数具有更“局部范围”。因此,你永远不会用两个新值来更新一个和。您可以通过更改参数的名称,使其与实例变量不同,或者将实例变量引用为this.d1this.d2,来解决这个问题