Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

complex conditions in switch statement is possible?

 
Mahendran Aiyappan
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

Is it possible to do the following condition in switch statement?
I know its crazy to do this using switch but my question is what level of support does switch statement provides.



Thanks,
Mahendran
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See "SwitchLabel" in the JLS: http://java.sun.com/docs/books/jls/third_edition/html/statements.html#258896
 
Chinna Eranna
Ranch Hand
Posts: 174
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You expresssion leads to a boolean ....
Switch expression cannot be "Boolean".
 
fred rosenberger
lowercase baba
Bartender
Posts: 12090
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
assuming i is an int, you could do this:



I wouldn't RECCOMEND it, but it could be done.
 
Rob Spoor
Sheriff
Pie
Posts: 20497
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That code is not the same because i < 10 && i > 20 will never be true. A number cannot be both smaller than 10 and larger than 20.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12090
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point. I guess i read it as an 'or'. giving up coffee sucks.
 
Mahendran Aiyappan
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correction please:



Thanks,
Mahendran
 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you want to use switch statement?

Anyways, The answer has already been given by Fred.



 
Campbell Ritchie
Sheriff
Posts: 48454
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could try switch (i / 10) . . ., but that is not exactly what you wrote.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic