• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 247
  • Last Modified:

switch with a string

Ola,

I want to do something like a switch but then for usage with strings.
as I understand switch is used switch ( int )

But how do i emulate switch ( String )

I am thinking of something like this
switch ( FunctionThatTransformsStringToInt( SomeStringVariable ) )
{
  case FunctionThatTransformsStringToInt( "SomeSting" ) :
}

how to make something like this work or what other ways are there?
0
DaFou
Asked:
DaFou
  • 3
1 Solution
 
petmagdyCommented:
the problem is "case" token only takes constant expersion, but u can do something like that:

public class SwitchString {
   
    public static void main(String[] args) {
        String color = "white";
       
        switch(color.hashCode())
        {
         case 12:
             System.out.println("Yellow!!");
         
        }
    }
}

assuming u know the hashCode values already
0
 
petmagdyCommented:
to clarify more like this:

public class SwitchString {
   
    public static void main(String[] args) {
        String color = "white";
        int yellowCode = "yellow".hashCode();
        int whiteCode = "white".hashCode();
         System.out.println(yellowCode);
         System.out.println(whiteCode);
        switch(color.hashCode())
        {
         case -734239628:
             System.out.println("Yellow!!");
         case 113101865:
             System.out.println("White!!");
         
        }
    }
}
0
 
petmagdyCommented:
also what is wrong with?:

if("while".equals(color) )
{

}
else if("yellow".equals(color) )
{

}
.....
0
 
DaFouAuthor Commented:
with more then 2 options anything other then a switch will result in performance loss
also using a switch statment one can group situation like

switch ( int )
{
  case 1 :
  case 2 :
    // do something
    break;
  case 3 :
  // do something else
}

and the switch simply looks much better then else if
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now