Java的两个Roll Dicer面向对象方式

时间:2018-11-14 18:30:00

标签: java

嗨,我是Java OOP的新手,我在运行程序时遇到一些问题

问题是没有输出,循环永不停止。

这是我的Main.java

public class Main {

    public static void main(String[] args) {

        Dice firstDie = new Dice();
        Dice secondDie = new Dice();
        do {
            count++;
            if(firstDie==secondDie ){
                same=true;
                System.out.println("It took "+count+ " times " + firstDie.getValue() + " and " + secondDie.getValue());
            }
        }
        while(!same);
    }
}

这是我的Dice.java

public class Dice {
    private int value;
    public Dice() {
        value = (int)(Math.random()*6)+1;
    } public int getValue() { return value; }

}
当我写int count = 0时在Main.java类中

;和boolean same = false;循环永无止境。

3 个答案:

答案 0 :(得分:0)

可能您必须比较值<script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div>firstDie.getValue()

您要尝试的是比较类secondDie.getValue()的2个实例。比较它们时,除非它们是同一对象,否则不能相同。 因此,Dice完全不成立,这会循环。

有关更多信息,请参见Java中的same方法,因为这是在比较两个实例/对象时调用的方法。

编辑: 即使您尝试下面的do-while代码段(即比较值equals()firstDie.getValue()

secondDie.getValue()

由于do { count++; int first = firstDie.getValue(); int sec = secondDie.getValue(); System.out.println(first+ " "+sec); if(first==sec ){ same=true; System.out.println("It took "+count+ " times " + first + " and " + sec); } } while(!same); 类的value仅被设置一次(即在构造函数中),因此仍然循环。 所以理想的方式是写,

Dice

答案 1 :(得分:0)

您正在比较类的实例,而不是它们中存储的值。 请注意,在println上,您引用的是每个骰子值(这是您要比较并具有匹配项的值),但是在比较中,您正在检查对象。

由于它们是2个不同的实例,因此它们将永远不会匹配,因此将不会有输出,循环也不会停止。

答案 2 :(得分:0)

尝试用firstDie.getValue() == secondDie.getValue()代替firstDie== secondDie

如果您说firstDie== secondDie,则正在检查两个实例是否相等。这两个永远都不相等。