Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Case switch

 
frank van schie
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do i make a case switch react to a string type instead of an integer?

 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By waiting for Java 7, which supports that, to be released.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49865
71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could try a switch on the hashCode of the String, but remember you have to work out the values after the case keyword before compiling; what follows "case" must be a compile-time constant.
 
Jasper Brown
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I needed to do this for a project and ended up using a long chain of if, else if ... statements. Very messy but it worked fine.

looked like

 
Stephan van Hulst
Bartender
Pie
Posts: 6129
74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code would probably be easier to read if you used enum constants:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic