Search code examples
javadicepoker

poker dice in java - not giving scores properly


I want to create a poker dice game in java, and when the player rolls the dice, I want the program to tell the results and the current score. However, something is wrong. It isn't giving me properly the score. For example, I changed the the Math Random algorithm to always give me always (1,1,1,1,1), so the result would be 50. Unfortunately,it is giving me 0. Can I have some help please? Thanks.

This is my code:

public class DiceGame {

    public static int [] rollDice() {
        int [] diceSide = new int[5];
        Random diceRoller = new Random();
         for (int i = 0; i<diceSide.length; i++) {
            int roll = diceRoller.nextInt(1) + 1;
            diceSide[i] = roll;
    }
         System.out.print(diceSide[0] + "" + diceSide[1] + "" + diceSide[2] + "" + diceSide[3] + "" + diceSide[4]);
         return diceSide; 
    }

    public static int getResult(int[] dice) {

        int resValue = 0;

        for (int i = 0; i < dice.length; i++) {
            if (dice[i] == 5) {
                resValue = 50;

            } else if (dice[i] == 4) {
                resValue = 40;          

            } else if (dice[i] == 3) {
                resValue = 30;     

            }
        }
        System.out.print(resValue); 
        return resValue;
    }


    public static void main(String[] args) {

        int player1=0;
        int player2;
        int player3;
        int player4;
        int player5;

        player1 += getResult(rollDice());
    }
}

Solution

  • Math.Random returns a value thats between 0 and 1. You have to multiply this value with the Max-Value you want to recieve - 1 and add +1 to the whole thing. Don't forget to cast this whole thing to (int). It should look something like this:

    (int) (Math.Random(5) + 1)
    

    This way, you're getting values between 1 and 6.