在java中使用switch case中的string [英] Use string in switch case in java

查看:256
本文介绍了在java中使用switch case中的string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将以下如果更改为开关 - 案例在检查字符串时,以提高圈复杂度。

I need to change the following if's to a switch-case while checking for a String, to improve the cyclomatic complexity.

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

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

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

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

但我不确定我会得到什么价值。

But I am not sure what value I'm going to get.

推荐答案

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

Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

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...
}

这篇关于在java中使用switch case中的string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆