-2

I have one class for showing my GUI called GUI and I have another class called Dice which should do some things for me.

First I only want to add the method createDice() which should create a random number and I want to show it in the console. It shows allways 1 in the console. Please help me. I am new here and I am exited about beeing a part of the community now :)

My Code:

    //returns new dice (number between 1 and 6)
    public int createDice () {
        int dice = (int) Math.random()*6+1;
        return dice;
    }
user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    @Ivar The moment I saw "xkcd" in your link, I *knew* it was *that* comic :-) – MC Emperor Aug 26 '21 at 07:17
  • It's better to use [`Random.nextInt(int bound)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) designed for this specific purpose: `return ThreadLocalRandom.current().nextInt(6) + 1;` – Nowhere Man Aug 26 '21 at 07:38

1 Answers1

1

Math.random returns a random number between 0 and 1. When you cast that to int you'll get a 0, 0*ANYNumber = 0, and 0 plus 1 is 1.

Solution: use parenthesis

(int) ((Math.random()*6) + 1);
Francisco Valle
  • 613
  • 10
  • 10
  • 2
    It's better to use [`Random.nextInt(int bound)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) designed for this specific purpose: `return ThreadLocalRandom.current().nextInt(6) + 1;` – Nowhere Man Aug 26 '21 at 07:38