-1

Hey guys I'm quite new to Java, and just started meddling with classes. I'm currently trying to simulate a dice on a basic game I'm creating. The dice seems to work, but I can only call it effectively once, as the number always remains the same after that. Is there an easy solution for the dice I've created to be difference every time I call it?

public class Dice {
  Random randomNum = new Random();

  public int diceRoll() {
    int diceResult = 0;
    int result = randomNum.nextInt(20) + 1;
    diceResult = diceResult + result;
    return diceResult;
  }
}

Appreciate any help in the slightest, thank you

Edit: Thank you for the feedback guys. It turned out my code was calling the original random value I used on an integer, as I didn't change its value to a new number everytime I was calling it.

Thanks again for helping me realize it wasn't the Dice class itself. Appreciate it! :)

AspiringNewbie
  • 113
  • 1
  • 7

3 Answers3

1

Tried your code, working fine.

import java.util.Random;
    public class Main {
        Random randomNum = new Random();
        public static void main(String[] args) throws Exception {
            Main main = new Main();
            for (int i =0; i<20; i++) {
                System.out.println(main.diceRoll());
            }
        }

        public int diceRoll()
        {
            int diceResult = 0;
            int result = randomNum.nextInt(20) + 1;
            diceResult = diceResult + result;
            return diceResult;
        }
    }

O/P

8
5
3
15
2
15
16
11
9
11
2
7
14
3
3
16
5
11
18
13

Can you please share your O/P

0

Have you tried instantiating the Random object inside your method like so?

public class Dice {


  public int diceRoll() {
    Random randomNum = new Random();
    int diceResult = 0;
    int result = randomNum.nextInt(20) + 1;
    diceResult = diceResult + result;
    return diceResult;
  }
}

The Random class is pseudo random and it's seeded by the date at the point of instantiation. You'd certainly get better random values in C#. It's worth giving this a go.

K-Dawg
  • 3,013
  • 2
  • 34
  • 52
0

Thank you for the feedback guys. It turned out my code was calling the original random value I used on an integer, as I didn't change its value to a new number everytime I was calling it.

Thanks again for helping me realize it wasn't the Dice class itself. Appreciate it! :)

AspiringNewbie
  • 113
  • 1
  • 7