我的方法不会接受对象

My method won't take an object

我正在制作一个掷骰子程序来模拟掷骰子给定的次数。首先,我创建一个具有给定边数的 Die 对象,然后在模拟滚动次数的滚动方法中使用该 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".

            }
        }   
    }
}

错误是:

the method is undefined for type Die cannot use this in a static context

此方法:

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方法没有在Dieclass中定义。为此:

Die sixSides = new Die(6);
sixSides.roll(7);

roll 必须在 Die class 中声明。这是因为您正试图调用 roll on 一个 Die 对象。

要修复这两个错误,只需将 roll 方法移动到 Die class!

你必须在 Die class

中定义一个 roll() 方法