I have this piece of code that produces a random ASCII character based on a random number generator from 65 to 90 (A-Z in ASCII) with a 50% chance it will be a letter or number.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 15; i++) {
if (random(0, 100) < 50) { //50% chance of it being a number or letter
sb.append((char) random(65, 90));
} else {
sb.append(random(0, 9));
}
}
Output:
9M0753YB840X370
Now, if we make it a little prettier and use a ternary operator, we get this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 15; i++) {
sb.append(random(0, 100) < 50 ? (char) random(65, 90) : random(0, 9));
}
Output:
69817716898127868775697285
The method that outputs random values:
public static int random(int min, int max) {
return (int) (Math.random() * (max - min + 1) + min);
}
I can't figure out why this isn't working as expected, since a ternary and an if
block should be equivalent in this case.
To summarise, the block of code if
works, but the ternary one doesn't.