简体   繁体   中英

dice game in java (calling from a class with a constructor)

I'm trying to make a dice game with a dice that can give a random number between 1 to 6. I have a class that is called Die which consist of one constructor and two methods. The constructors main purpose is to initiate a random value and the two methods should roll the dice and return the value respectively. My problem is that I don't know how to roll the dice and retrieve the number after I have made an object.

import java.util.Random;

class Die{
    int dots,roll;
    Random number = new Random();

    public Die(){
        int dots = number.nextInt(6)+1 ;
    }

    public void roll(){
        roll = number.nextInt(dots)+1;
    }

    public int getDots(){
        return roll;
    }

}

public class Uppg1 {
    public static void main (String args[]){
        Die die = new Die();
        System.out.println("Du fick "+die.getDots());

    }
}

It appears that my code goes to the constructor and not to methods. I want the value from the constructor and then roll the dice and then get the value from method getDots.

Inside Die constructor you update internal dots variable instead of class member. Use:

public Die(){
    dots = number.nextInt(6)+1 ;
}
  int dots = number.nextInt(6)+1 ;

This is different variable from the variable

class Die{
    int dots,roll;

so make it

dots = number.nextInt(6)+1 ;

so that you will get the right value.

I have modified the code for you just take a look:import java.util.Random;

class Die{
    int dots,roll;
    Random number = new Random();

    public Die(){
         dots = number.nextInt(6)+1 ;
    }

    public void roll(){
        roll = number.nextInt(dots)+1;
    }

    public int getDots(){

        return roll;
    }

}

public class Uppg1 {
    public static void main (String args[]){
        Die die = new Die();
        die.roll();
        System.out.println("Du fick" +die.getDots());

    }
}

remove int from Die constructor as it already defined as global, your prog. doesn't call roll method anywhere hence need to call that.

int dots = number.nextInt(6)+1 does not change the field dots but creates a new variable dots

Additionally you never call roll() so roll=null and getDots() returns null.

You can roll the dice by calling die.roll() in the Uppg1 main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM