我的方法不会拿一个物体

时间:2017-07-10 17:01:53

标签: java dice

我制作一个骰子滚动程序来模拟滚动模具一定次数。首先,我创建一个具有给定数量边的Die对象,然后在roll方法中使用该Die,模拟它将被滚动的时间。

有人可以澄清吗?

public class Die {

    private int numSides;

    public Die() {
        numSides = 0;
    }

    public Die(int sides){
        numSides = sides; 
    }

    public void setSides(int sides){
        numSides = sides;
    }

    public int getSides(){
    return numSides;
    }
}

public class DiceRoll {

    public static void main(String []args){


        Die sixSides = new Die(6);
        sixSides.roll(7); //ERROR: "the method is undefined for type Die" 


        //Prints out the roll outcomes for the given die
        public void roll(int numTimes){
            for (int i = 0; i < numTimes; i++){
                int rand = 1 + (int)(Math.random()*this.getSides());
                System.out.println(rand);
            //ERROR: "cannot use THIS in a static context".

            }
        }   
    }
}

错误是:

  

对于Die类型,该方法未定义   不能在静态上下文中使用它

2 个答案:

答案 0 :(得分:1)

您必须在roll()

中定义Die方法

答案 1 :(得分:0)

此方法:

public void roll(int numTimes){
    for (int i = 0; i < numTimes; i++){
        int rand = 1 + (int)(Math.random()*this.getSides());
        System.out.println(rand);
    }
} 

目前在main方法中声明,该方法首先无效。您无法在方法中声明方法。这解释了第二个错误。 main是静态的,因此您无法在其中使用this

发生第一个错误是因为roll类中未定义Die方法。为此:

Die sixSides = new Die(6);
sixSides.roll(7);
必须在roll类中声明

Die。这是因为您尝试在 roll对象上调用Die

要解决这两个错误,只需将roll方法移至Die类!