# Ternary Operator (?:) Questions

• 12-11-2013, 04:51 PM
Mind Blown
Ternary Operator (?:) Questions
I had quite a hard time figuring this out my self (it came from the book and I am trying to analyze it) but... pff <_< no hope. Been trying to figure it out for an hour and yet I still couldn't get it.

So here is the question:

- How to convert this if/else statement using the ternary (?:) operator?
Code:

```double value = 8.9; if (value > 10.6)     System.out.println("x is greater than 10. \n"); else     System.out.println("x is less than or equal to 10. \n");```

If you do know it, please tell me what you did and how did you done it (line by line) if you may so that I can understand it properly.

• 12-11-2013, 04:58 PM
PhHein
Re: Ternary Operator (?:) Questions
As it is only one line it's hard to tell line by line:
Code:

` System.out.println(value > 10.6?"x is greater than 10. \n":"x is less than or equal to 10. \n");`
• 12-11-2013, 05:01 PM
gimbal2
Re: Ternary Operator (?:) Questions
I think the intended result is that those four lines of the if/else statements turn into 1 line that does a single System.out, so there is no "line by line" to speak of.

Okay lets say I give you a simple example and not solve the riddle for you directly.

Code:

```boolean truthOrDare = true; String text = truthOrDare ? "truth" : "dare";```
Can you then apply this to your problem?

EDIT: ninja'd by the spoonfeeding PhHein! Tsk tsk.
• 12-11-2013, 05:01 PM
Mind Blown
Re: Ternary Operator (?:) Questions
Quote:

Originally Posted by PhHein
As it is only one line it's hard to tell line by line:
Code:

` System.out.println(value > 10.6?"x is greater than 10. \n":"x is less than or equal to 10. \n");`

Heh, my bad I've no idea actually.

Now I finally understand it.
Thanks man.
• 12-11-2013, 05:05 PM
PhHein
Re: Ternary Operator (?:) Questions
Quote:

Originally Posted by gimbal2
EDIT: ninja'd by the spoonfeeding PhHein! Tsk tsk.

Yeah, sorry, mate. I couldn't think of a non spoonfeeding way. I'm not as creative as you :)

Phil
• 12-11-2013, 05:58 PM
gimbal2
Re: Ternary Operator (?:) Questions
Not sure if serious or poking fun at me in return... I hope the latter.
• 12-11-2013, 07:37 PM
JosAH
Re: Ternary Operator (?:) Questions
Quote:

Originally Posted by gimbal2
Not sure if serious or poking fun at me in return... I hope the latter.

You could do this:

Code:

`System.out.println("x is "+(value > 10.6?"great than":"less than or equal to")+" "+(42-32));`
kindest regards,

Jos
• 12-12-2013, 10:49 AM
PhHein
Re: Ternary Operator (?:) Questions
Quote:

Originally Posted by gimbal2
Not sure if serious or poking fun at me in return... I hope the latter.

The latter, of course.
• 12-12-2013, 10:55 AM
JosAH
Re: Ternary Operator (?:) Questions
Quote:

Originally Posted by PhHein
The latter, of course.

<high squeaky voice>
You're lying old woman! Now confess! It was the first! Confess!
</high squeaky voice>

kindest regards,

The Spanish Inquisition