aspose file tools*
The moose likes Beginning Java and the fly likes switch statement on String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

switch statement on String

vitesse wei
Ranch Hand

Joined: Sep 07, 2007
Posts: 100
Hi,I have two string variables,they could have 20x5 combinations,how can i implement the code to check on specific combination,"if else" is not good design,I can not use "switch" on string,"enum" is not good too,what is the better solution for this?


SCJP 5.0<br />SCWCD1.4<br />SCBCD5
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Being able to switch on a String is a proposed feature of Java 7 due out in early 2010. Assuming waiting until then is not an option there's a couple of things you could do.

The thing I would ask is what is going to be the contents of the conditional block? Is there a lot of logic in it? If it's just a matter of assigning a value to something (or a couple of things), you could just use a Map with the String as the Key. The value would be either the value you need, or an object that either contains a couple of values, or even possibly the logic needed. A sort of Strategy pattern.

Can you provide a little more detail as to what you are trying to do, especially what needs to happen in the conditional block, and some other ideas might come to mind.
Graeme Byers
Ranch Hand

Joined: Apr 16, 2004
Posts: 127
Two suggestions :
1. switch can take a primitive char - try converting each String letter to char and then hashing (unique - two values + few valid combinations)
2. switch can take a function that returns an int


A few remarks :
The Case construct (language independent) was intended to allow easier coding of nested conditional statements.

Java's implementation is a complete dog.
1. Without break ; it is a "goto depending on the value of a variable"
2. Even Cobol's Case (called EVALUATE) can take a "string" or any numeric primitive.
Cobol can also handle any conditional,since they return a boolean value
3. To Cobol , PL/1 adds the requirement that if no default is coded (empty default is OK) and no case statement is executed then an exception is thrown.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8971
    
    9

Please do not post the same question more than once. It wastes peoples time when multiple conversations take place.
CarefullyChooseOneForum


[How To Ask Questions On JavaRanch]
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42622
    
  65
Let's continue the discussion in the duplicate thread Joe linked to.


Ping & DNS - my free Android networking tools app
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: switch statement on String