File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Ternary operator cannot get it to work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Ternary operator cannot get it to work" Watch "Ternary operator cannot get it to work" New topic
Author

Ternary operator cannot get it to work

Tanya Ruttenberg
Ranch Hand

Joined: Jun 22, 2009
Posts: 40
I can not get the ternary operator to work.

What is wrong with this code?



I'm getting these compile errors from eclipse.

Multiple markers at this line
- Syntax error on token "?", ; expected
- Syntax error on token ":", ; expected


But of course if I put in the semi-colons, it does not help:

Multiple markers at this line
- Syntax error on token ":", invalid EmptyStatement
- Syntax error on token "?", delete this token



I have this same problem every time I try to use the ternary operator. What the heck am I doing wrong?

Thank you in advance.

TDR
Carey Brown
Ranch Hand

Joined: Nov 19, 2001
Posts: 174

The expressions to the right of '?' and ':' must evaluate to data of some type. Neither 'throw' nor 'return' meets this qualification.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19674
    
  18

Correct. You can't put statements in the ternary operator, only values. These values may be the results of method calls but they must still be values. That means you can't put a System.out.println() or a throw statement there.

I'm afraid you will need to use a normal if-statement here:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Ternary operator cannot get it to work