This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Customer Requirements for Developers and have Marcho Behler on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Case switch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Customer Requirements for Developers this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Case switch" Watch "Case switch" New topic
Author

Case switch

frank van schie
Greenhorn

Joined: May 16, 2011
Posts: 7
How do i make a case switch react to a string type instead of an integer?

Paul Clapham
Sheriff

Joined: Oct 14, 2005
Posts: 19693
    
  10

By waiting for Java 7, which supports that, to be released.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 43399
    
  32
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

Joined: May 31, 2011
Posts: 3
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

Joined: Sep 20, 2010
Posts: 3905
    
  18

The code would probably be easier to read if you used enum constants:


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
 
Consider Paul's rocket mass heater.
 
subject: Case switch
 
It's not a secret anymore!