首页 文章

在java中使用switch case中的string

提问于
浏览
55

我需要在检查 String 时将以下 if 更改为 switch - case ,以提高圈复杂度 .

String value = some methodx;
if ("apple".equals(value)) {
    method1;
}

if ("carrot".equals(value)) {
    method2;
}

if ("mango".equals(value)) {
    method3;
}

if ("orange".equals(value)) {
    method4;
}

但我不确定我会得到什么 Value .

13 回答

  • 0
    String value = someMethod();
    switch(0) {
    default:
        if ("apple".equals(value)) {
            method1();
            break;
        }
        if ("carrot".equals(value)) {
            method2();
            break;
        }
        if ("mango".equals(value)) {
            method3();
            break;
        }
        if ("orance".equals(value)) {
            method4();
            break;
        }
    }
    
  • 15

    Java(版本7之前)不支持switch / case中的String . 但是你可以通过使用枚举来达到预期的效果 .

    private enum Fruit {
        apple, carrot, mango, orange;
    }
    
    String value; // assume input
    Fruit fruit = Fruit.valueOf(value); // surround with try/catch
    
    switch(fruit) {
        case apple:
            method1;
            break;
        case carrot:
            method2;
            break;
        // etc...
    }
    
  • 0

    学习使用 else .

    由于 value 永远不会同时等于两个不相等的字符串,因此只有5种可能的结果 - 一个用于您关心的每个值,另外一个用于"none of the above" . 但是因为你的代码没有传递,它有16个"possible"路径(2 ^测试次数),其中大多数都不会被遵循 .

    使用 else ,存在的唯一路径是实际可能发生的5 .

    String value = some methodx;
    if ("apple".equals(value )) {
        method1;
    }
    else if ("carrot".equals(value )) {
        method2;
    }
    else if ("mango".equals(value )) {
        method3;
    }
    else if ("orance".equals(value )) {
        method4;
    }
    

    或者开始使用JDK 7,它包括在 switch 语句中使用字符串的功能 . 当然,Java只会将 switch 编译成 if / else 类似的构造...

  • 1

    现在每个人都至少使用Java 7,对吧?这是原始问题的答案:

    String myString = getFruitString();
    
    switch (myString) {
    
        case "apple":
            method1();
            break;
    
        case "carrot":
            method2();
            break;
    
        case "mango":
            method3();
            break;
    
        case "orange":
            method4();
            break;
    }
    

    Notes

    • case语句等同于使用 String.equals .

    • 像往常一样,字符串匹配区分大小写 .

    • 根据docs,这通常比使用链式 if - else 语句更快(如cHao's answer) .

  • 0

    要减少圈复杂度,请使用 Map :

    Map<String,Callable<Object>> map = new HashMap < > ( ) ;
    map . put ( "apple" , new Callable<Object> () { public Object call ( method1 ( ) ; return null ; } ) ;
    ...
    map . get ( x ) . call ( ) ;
    

    或多态性

  • 164

    只是为了得到具体的emory答案,可执行代码如下:

    Map<String,Callable<USer>> map = new HashMap<String,Callable<User>>();
      map.put( "test" , new Callable<User> () { public User call (){ return fillUser("test" ); }} ) ;
      map.put( "admin" , new Callable<Utente> () { public Utente call (){  return fillUser("admin" ); }} ) ;
    

    其中user是POJO,然后是

    User user = map.get(USERNAME).call();
    

    最后被调用的方法是某个地方:

    private User fillUser(String x){        
            User user = new User();
            // set something in User
            return user;
    }
    
  • 0

    Java不支持带字符串的Switch-case . 我猜this链接可以帮到你 . :)

  • 0

    这是一种可能的1.7之前的方法,我不建议:

    public class PoorSwitch
    {
        final static public int poorHash (String s) {
            long l = 0L;
            for (char c: s.toCharArray ()) {
                l = 97*l + c;
            }
            return (int) l;
        }
    
        public static void main (String args[])
        {
            String param = "foo";
            if (args.length == 1)
            {
                param = args[0];
            }
            // uncomment these lines, to evaluate your hash
            // test ("foo");
            // test ("bar");
            switch (poorHash (param)) {
                // this doesn't work, since you need a literal constant
                // so we have to evaluate our hash beforehand:
                // case poorHash ("foo"): {
                case 970596: {
                    System.out.println ("Foo!");
                    break;
                }
                // case poorHash ("bar"): {
                case 931605: {
                    System.out.println ("Bar!");
                    break;
                }
                default: {
                    System.out.println ("unknown\t" + param);
                    break;
                }
            }
        }
    
        public static void test (String s)
        {
            System.out.println ("Hash:\t " + s + " =\t" + poorHash (s));
        }
    }
    

    也许你可以在生成的代码中使用这样的技巧 . 否则我不推荐它 . 并非如此,哈希冲突的可能性让我担心,但如果某些事情混淆(剪切和粘贴),很难找到错误 . 931605不是一个好的文档 .

    把它当作好奇心的概念证明 .

  • 16

    我们可以只在数据类型兼容的int上应用Switch:short,Shor,byte,Byte,int,Integer,char,Character或enum type .

  • 5

    使用switch语句评估 String 变量已在Java SE 7中实现,因此它仅适用于java 7.您还可以查看在JDK 7中如何实现此新feature .

  • -10

    Java 8支持字符串switchcase .

    String type = "apple";
    
    switch(type){
        case "apple":
           //statements
        break;
        default:
           //statements
        break; }
    
  • -1
    String name,lname;
     name= JOptionPane.showInputDialog(null,"Enter your name");
       lname= JOptionPane.showInputDialog(null,"Enter your father name");
        if(name.equals("Ahmad")){
           JOptionPane.showMessageDialog(null,"welcome "+name);
        }
        if(lname.equals("Khan"))
       JOptionPane.showMessageDialog(null,"Name : "+name +"\nLast name :"+lname ); 
    
        else {
           JOptionPane.showMessageDialog(null,"try again " );
        } 
      }}
    
  • 0

    不是很漂亮,但这是另一种方式:

    String runFct = 
            queryType.equals("eq") ? "method1":
            queryType.equals("L_L")? "method2":
            queryType.equals("L_R")? "method3":
            queryType.equals("L_LR")? "method4":
                "method5";
    Method m = this.getClass().getMethod(runFct);
    m.invoke(this);
    

相关问题