Java Sum Of Two Dice Will This Code Give Above A 6?

public class SumOfTwoDice 
{ 
    public static void main(String[] args) 
    {
        int SIDES = 6;
        int a = 1 + (int) (Math.random() * SIDES);
        int b = 1 + (int) (Math.random() * SIDES);
        int sum = a + b;
        System.out.println(sum);
    }
}

I've taken this code from the book "Introduction to Programming with Java" by Sedgewick on their online website.

I just have a question as to whether a or b could possibly be above 6 if by chance Math.random() is 1.0? Or am I wrong on this?

1.0 * 6 + 1 = 7?

Jon Skeet
people
quotationmark

No, Math.random() will never return 1. It has an inclusive lower bound of 0, but an exclusive upper bound of 1.0. From the documentation - emphasis mine:

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Now given that this is floating point maths, you still need to consider whether there's some value less than 1 such that when multiplied by 6, the closest representable double is 6 rather than some value just below 6... but I don't believe that's a problem here.

It would still be clearer to use java.util.Random though....

private static final int SIDES = 6;

public static void main(String[] args) {
    Random random = new Random();
    int a = random.nextInt(SIDES) + 1;
    int b = random.nextInt(SIDES) + 1;
    int sum = a + b;
    System.out.println(sum);
}

people

See more on this question at Stackoverflow