-2

What does the following line do? Could someone help me write this line in "normal" code?

int change = (Math.random() - 0.5 < 0 ? -5 : 5);
Meatball
  • 185
  • 1
  • 9

2 Answers2

4

This is a ternary operator the way it works is :

   condition ? (things to do if true) : (things to do if false);

In your code what it does is :

if value of  Math.random() - 0.5 < 0 
   then assign change a values of -5 
else 
    assign change a value of 5.
Kakarot
  • 4,252
  • 2
  • 16
  • 18
  • To be more precise, it's actually an _expression_ that evaluates as `condition ? (value if true) : (value if false)`. Neither one of them changes the value of `change` in this code; rather, the whole ternary expression evaluates to one expression or the other (in this case, `-5` or `5`), and, separately, the `change = ` part assigns that value to `change`. – yshavit May 20 '14 at 19:42
2

This line takes a random number (between 0 and 1) and subtracts 0.5. If that value is less than 0 then change is set to -5, otherwise 5.

int change;
if((Math.random() - 0.5) < 0)
{
  change=-5;
}
else
{
  change=5;
}
shrub34
  • 796
  • 6
  • 17