【问题标题】:Java - Enumerated types in IF statementsJava - IF 语句中的枚举类型
【发布时间】:2016-01-04 03:02:10
【问题描述】:

所以对于我的基本代码,我很好奇是否可以有如下的 if 语句:

if (ScannerInput.equalsIgnoreCase(AllEnums)){
    System.out.println("Sample");
}

如果您理解我希望仅使用 Enum 的名称,例如它对所有值都是正确的。如果可以的话,我该怎么做?

这是我的意思的一个例子:

import java.util.Scanner;

public class EnumTest {
    enum Weather {Sunny, Rainy, Snowy, Overcast, Stormy};

    public static void main (String[] args) {
        Scanner scan = new scanner(System.in);
        String userinput = nextLine;

        if (userinput.equalsIgnoreCase(Weather.all) // I wish for this to occur if any of the Weather enums are entered.
            System.out.println ("Working!");
        }
    }
}

【问题讨论】:

  • 恐怕我不明白。你能举一个enum 的例子和你想要的ScannerInput 吗?

标签: java if-statement enums enumerated-types


【解决方案1】:

好吧,我想我有点困惑,也许试试这样?

for(Test t:Test.values()){
    if(ScannerInput.equals(t)){
        System.out.println("Sample");
    }
}

【讨论】:

    【解决方案2】:
    enum Color { RED, GREEN, BLUE }
    
    String input = ...
    
    try {
        Color c = Color.valueOf(input.trim().replace(' ', '_').toUpperCase());
        ...
    } catch (IllegalArgumentException e) {
        ...
    }
    

    在您的情况下,您需要来自 apache commons 的 StringUtils.capitalize 之类的东西。或者使用只有大写的枚举常量的约定。 (在 java.awt.Color 的情况下,他们无法决定并且也有所有小写字母版本。)

    【讨论】:

      【解决方案3】:

      您可以向您的enum-class 添加一个方法来检查值是否在该枚举中:

      public boolean contains(String s) {
          for (YourEnum yourEnum : values()) {
              return yourEnum.toString().equalsIgnoreCase(s);
          }
          return false;
      }
      

      但这需要一个近乎完美的匹配,考虑到有人在控制台(或类似设备)上输入值,这是不可靠的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多