Search code examples
javadice

My method won't take an object


I'm making a dice rolling program to simulate rolling a die a given number of times. First I create a Die object with a given number of sides, and then use that Die in a roll method that simulates the number of time it will be rolled.

Can someone clarify?

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 Error is:

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


Solution

  • This method:

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

    is currently declared in the main method, which is invalid in the first place. You cannot declare a method inside a method. This explains the second error. main is static so you can't use this in there.

    The first error occurs because the roll method is not defined in the Die class. For this to work:

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

    roll must be declared in the Die class. This is because you are trying to call roll on a Die object.

    To fix both errors, just move the roll method to the Die class!