gpt4 book ai didi

java - 如何在Java中使用对象方法?

转载 作者:行者123 更新时间:2023-12-02 11:21:58 25 4
gpt4 key购买 nike

我的任务是使用 Java 创建一个相当简单的基于骰子的棋盘游戏。我已经初始化了构造函数中的所有骰子对象,但是当我尝试使用游戏类内的骰子类中的方法时,出现错误(对象名称)无法解析。如果解释不清楚,请原谅我,但希望代码会更有意义。该错误是在qwixx类的rollDice()方法中遇到的。

public class qwixx {

public qwixx() {
dice white1 = new dice();
dice white2 = new dice();
dice red = new dice();
dice yellow = new dice();
dice green = new dice();
dice blue = new dice();
}

public void rollDice() {
white1.rollDice();
white2.rollDice();
red.rollDice();
yellow.rollDice();
green.rollDice();
blue.rollDice();
}

}
<小时/>
public class dice {

String colour;
int currentSide;

public dice() {
colour = "white";
rollDice();
}

public int rollDice() {
currentSide = (int)(Math.random() * 6 + 1);
return currentSide;
}

}

最佳答案

构造函数中的所有变量都必须在类级别声明。

public class qwixx {
// declare the dice variables at the class level (as 'fields')
dice white1;
// same for other dice : declare them here

public qwixx() {
// in the constructor you actually create the object and assign references to the class variables
white1 = new dice();
// idem for others
}
}

这就是类中的所有方法都可以访问这些字段的方式。

否则,您的骰子引用将仅在声明它们的方法、构造函数中可见,当然这不是您想要的,也是导致错误的原因。

关于java - 如何在Java中使用对象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49848823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com