Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中使用对象方法?_Java - Fatal编程技术网

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

如何在Java中使用对象方法?,java,Java,我的任务是使用Java创建一个相当简单的基于骰子的棋盘游戏。我已经初始化了构造器中的所有骰子对象,但是当我尝试从游戏类中的骰子类中创建一个方法时,我发现错误(对象名)无法解决。如果这个解释不清楚,请原谅,但希望代码会更有意义。qwixx类的rollDice()方法中遇到错误 public class qwixx { public qwixx() { dice white1 = new dice(); dice white2 = new dice();

我的任务是使用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 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
    }
}
这就是类中的所有方法可以访问这些字段的方式


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

感谢快速解决方案,假设我想打印出所有骰子当前边的值。为什么这样的东西不起作用呢?System.out.println(“红色骰子:+Red.currentSide+”;黄色骰子:+Yellow.currentSide+”;绿色骰子:+Green.currentSide+”;蓝色骰子:+Blue.currentSide+”;白色骰子:+White1.currentSide+”;白色骰子:+white2.currentSide);在面向对象编程中,需要使用“getCurrentSide()”之类的方法,而不是直接访问字段,这是一种更好的做法。但正如您已经注意到的,这并不是NullPointerException的原因。“不工作”非常模糊,请在描述代码问题时避免使用此短语。如果您的意思是您有nullPointerException,那么这意味着您正在尝试在创建至少一个对象之前执行上述代码(使用
yourfield=new dice();
)。某个引用仍然是
null
,并且您正在尝试对null引用调用一个方法。明白了。是的,我的意思是返回nullPointerException。
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
    }
}