What was I thinking?


What on earth…

I just found a very stupid code that I wrote a few weeks ago.

switch (ThreadLocalRandom.current().nextInt() % 2) {
    case 1:
        return ...;
    case 2:
        return ...;
    default:
        return ...;
}

What on earth was I thinking? According to those three case: blocks including default:, it seems that I intended to randomize for three conditions.

%!

The % 2 part is definitely wrong. For any positive left operands, % operator returns 0, 1, …, n-2, n-1 for the right operand ‘n’.

switch (ThreadLocalRandom.current().nextInt() % 3) {
    case 0:
        return ...;
    case 1:
        return ...;
    default: // 2
        return ...;
}

java.util.Random#nextInt()

The nextInt() method returns not just one of positive integers but also any negative integers.

switch (ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE) % 3) {
    case 0:
        return ...;
    case 1:
        return ...;
    default: // 2
        return ...;
}

%?

I think I don’t really have to be bothered with ‘%’.

switch (ThreadLocalRandom.current().nextInt(3)) {
    case 0:
        return ...;
    case 1:
        return ...;
    default: // 2
        return ...;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s