-2

Instead of typing :

if (Math.random() < .5) {
    System.out.println("toto");
} else {
    System.out.println("tata");
}

I would find it useful, and logical, to type instead :

Math.random() < .5 ? System.out.println("toto") : System.out.println("tata");

However, I get the error not a statement. I don't understand how this is an issue.

J. Schmidt
  • 419
  • 1
  • 6
  • 17
  • 4
    The conditional operator is for evaluating expressions, not executing statements. `System.out.println("todo")` is not an expression: it doesn't have any value. The `if` statement is for executing statements, so use that. – khelwood Jul 24 '20 at 09:40
  • 1
    You can do this: `String answer = Math.random() < .5 ? "toto" : "tata" ; System.out.println(answer); ` – Chetan Gupta Jul 24 '20 at 09:41
  • 3
    Or in one line: `System.out.println(Math.random() < .5 ? "toto" : "tata");` – Stephen C Jul 24 '20 at 09:43

1 Answers1

2

Because the ternary operator assigns a value to a variable. Change it to:

String toPrint = Math.random() < .5 ? "toto" : "tata";
System.out.println(toPrint);
Marc
  • 2,738
  • 1
  • 17
  • 21