java - 在java中的switch case中使用字符串

标签 java string switch-statement

在检查 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)。

最佳答案

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

关于java - 在java中的switch case中使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10240538/

相关文章:

switch 语句中第一个 'case' 之前的代码

python - 如何在字符串中搜索子字符串值?

c++ - 调用 `strcat` 并能够将较大的字符串存储到较小的字符串中?

java - Maven项目 "AmazonS3ClientBuilder() has private access in com.amazonaws.services.s3.AmazonS3ClientBuilder"

java - 什么是带断点的线程的程序计数器?

string - 如何以递归方式思考?

c - 通过 for 循环切换大小写声明?

android-layout - 切换与切换

java - 合并两个 Jasper 报告

java - 如何在Lucene中正确使用multireader API?