Results 1 to 4 of 4
  1. #1
    Billywizz is offline Member
    Join Date
    Jan 2011
    Posts
    57
    Rep Power
    0

    Default Shorthand ternary operator ?

    Hi all,
    just wondering if it is possible to write three cases of an if statement as a shorthand ternary operator for example:

    if(x==1)
    a=10;
    else if (x==2)
    a=x*2;
    else
    a=33333;

    so far i have:
    a = x == 1 ? 10 : 4 ;

    this only sets a to either 10 or 4 if x = 1 a = 10 if not a = 4. How do i put the third case in so that a = 4 if and only if x == 2 else a = 3333

    All help appreciated.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    Billywizz is offline Member
    Join Date
    Jan 2011
    Posts
    57
    Rep Power
    0

    Default Re: Shorthand ternary operator ?

    thank you. so it should only really be used for 2 cases if the statement is true do this. else do this.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Shorthand ternary operator ?

    In my opinion, yes. Sure, you could always do
    Java Code:
    a = x == 1 ? 10 : x == 2 ? 2 * a : 3333;
    But try to debug it 1 month or even 1 week later, and what then?

Similar Threads

  1. Java OR operator || help!
    By BeardedCamel in forum New To Java
    Replies: 2
    Last Post: 09-19-2011, 08:55 PM
  2. doubt regarding ternary operator (?)
    By subith86 in forum New To Java
    Replies: 2
    Last Post: 03-10-2011, 08:15 AM
  3. Use of ternary
    By wulfgarpro in forum New To Java
    Replies: 1
    Last Post: 09-21-2010, 06:31 AM
  4. Replies: 2
    Last Post: 02-27-2010, 07:10 AM
  5. Shorthand ?
    By gatzke in forum New To Java
    Replies: 5
    Last Post: 07-29-2009, 02:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •