Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to avoid multiple if-else if(say 25 conditions)?

 
Senthil Kumar Sekar
Ranch Hand
Posts: 45
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have say 25 if-else if conditions.So,should i have only 25 if-else if conditions.
Is there any better/effective way of checking it?
The disadvantage i see here is, if the condition satisfies only at 25th condition, it needs to check unnecessarily for 24 conditions.

PS : if-else if check i mean here can be anything (From String literal to an Object).


Please suggest.

Thanks.

Regards
Senthil Kumar Sekar
 
john price
Ranch Hand
Posts: 495
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Is that what you were looking for? Maybe a while statement?
cc11rocks

EDIT : The poster below has a better solution. Java 7 comes out July 28, 2011 FYI
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks like you want a powerful SWITCH that accepts non integers too. I wanted it too. This is what is available as of now : In Java SE 7 and later, you can use a String object in the switch statement's expression.
See - http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Right now , I am trying to make code that will take objects too. I failed !
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another solution might be to use a Map. I don't know exactly what expressions you have in your if-statements, so I can't tell you if this will work for your situation. But suppose that your chain of if-statements looks something like this:

You could do that with a Map like this:

 
Maneesh Godbole
Saloon Keeper
Posts: 11196
15
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The disadvantage i see here is, if the condition satisfies only at 25th condition, it needs to check unnecessarily for 24 conditions.

Your question might be of academic intrest but I seriously doubt the 24 checks would result in a noticeable performance lag.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic