0

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.

Morgan
  • 907
  • 1
  • 13
  • 35
  • 2
    They are not equivalent. In the first snippet, you're using two `append` overloads, typed differently, one with `char` and one with `int`. In the second examples, you're only using the one `append` with a parameter of type `int`. – Sotirios Delimanolis Sep 08 '17 at 16:49
  • IIRC both sides of the `:` must have the same type. So the `char` side is being converted to `int`. (Notice that your output got longer even though your loop is only appending 15 times) – 0x5453 Sep 08 '17 at 16:50
  • @SotiriosDelimanolis Oh hell, that makes sense. Thank you. – Morgan Sep 08 '17 at 16:50
  • 1
    @SotiriosDelimanolis added one to the duplicate list. I hope you don't mind. –  Sep 08 '17 at 16:51
  • See http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25.3 – Adam Sep 08 '17 at 16:52

0 Answers0