Bookmark Topic Watch Topic
  • New Topic

switch statement on String

 
vitesse wei
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Report post to moderator
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?
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 127
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 9295
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
Please do not post the same question more than once. It wastes peoples time when multiple conversations take place.
CarefullyChooseOneForum
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Report post to moderator
Let's continue the discussion in the duplicate thread Joe linked to.
 
    Bookmark Topic Watch Topic
  • New Topic