Java 将字符串与枚举值进行比较的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9858118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:23:15  来源:igfitidea点击:

What's the proper way to compare a String to an enum value?

javaenums

提问by dwwilson66

Homework: Rock Paper Scissors game.

作业:石头剪刀布游戏。

I've created an enumeration:

我创建了一个枚举:

      enum Gesture{ROCK,PAPER,SCISSORS};

from which I want to compare values to decide who wins--computer or human. Setting the values works just fine, and the comparisons work properly (paper covers rock, rock crushes scissors, scissors cuts paper). However, I cannot get my tie to work. The user is declared as the winner any time there's a tie.

我想从中比较值来决定谁获胜——计算机还是人类。设置值工作得很好,比较工作正常(纸盖石头,石头压剪刀,剪刀剪纸)。但是,我不能让我的领带工作。任何时候出现平局,用户就会被宣布为获胜者。

Ahhh...crap...this will clarify: userPickis a Stringwith values rock, paper, or scissors. I'm unable to use ==to compare userPickto computerPick, which, as you can see below, is cast as type Gesturefrom my enum.

唉唉......废话......这将澄清:userPick是一个String具有价值rockpaperscissors。我无法使用==to compare userPickto computerPick,正如您在下面看到的,它是Gesture从我的enum.

      if(computer == 1)
         computerPick = Gesture.ROCK;
      else
         if(computer == 2)
           computerPick = Gesture.PAPER;
         else
           computerPick = Gesture.SCISSORS;
      if(userPick.equals(computerPick))
       {
          msg = "tie";
          ++tieGames;
       }
           etc....

I am guessing that there's an issue with rocknot being equal to ROCK, or the String userPicknot being able to match Gesture computerPickbecause the latter isn't a String. However, I'm not able to find an example of a similar circumstance in my textbook or Oracle's Java Tutorials, so I'm not sure how to correct the problem...

我猜测存在rock不等于的问题ROCK,或者String userPick无法匹配,Gesture computerPick因为后者不是String. 但是,我无法在我的教科书或 Oracle 的 Java 教程中找到类似情况的示例,因此我不确定如何解决问题...

Any hints?

任何提示?

采纳答案by Ted Hopp

I'm gathering from your question that userPickis a Stringvalue. You can compare it like this:

我从你的问题中收集userPick了一个String有价值的信息。你可以这样比较:

if (userPick.equalsIgnoreCase(computerPick.name())) . . .

As an aside, if you are guaranteed that computeris always one of the values 1, 2, or 3(and nothing else), you can convert it to a Gestureenum with:

顺便说一句,如果您保证它computer始终是值1, 2, or 3(没有别的)之一,您可以将其转换为Gesture枚举:

Gesture computerPick = Gesture.values()[computer - 1];

回答by kandarp

You should declare toString()and valueOf()method in enum.

你应该申报toString(),并valueOf()在方法enum

 import java.io.Serializable;

public enum Gesture implements Serializable {
    ROCK,PAPER,SCISSORS;

    public String toString(){
        switch(this){
        case ROCK :
            return "Rock";
        case PAPER :
            return "Paper";
        case SCISSORS :
            return "Scissors";
        }
        return null;
    }

    public static Gesture valueOf(Class<Gesture> enumType, String value){
        if(value.equalsIgnoreCase(ROCK.toString()))
            return Gesture.ROCK;
        else if(value.equalsIgnoreCase(PAPER.toString()))
            return Gesture.PAPER;
        else if(value.equalsIgnoreCase(SCISSORS.toString()))
            return Gesture.SCISSORS;
        else
            return null;
    }
}

回答by oiyio

You can do it in a simpler way , like the below:

你可以用更简单的方式来完成,如下所示:

boolean IsEqualStringandEnum (String str,Enum enum)
{
  if (str.equals(enum.toString()))
     return true;
  else
     return false;
}

回答by Rami Del Toro

This seems to be clean.

这似乎很干净。

public enum Plane{

/**
 * BOEING_747 plane.
 */
BOEING_747("BOEING_747"),

/**
 * AIRBUS_A380 Plane.
 */
AIRBUS_A380("AIRBUS_A380"),

;

private final String plane;       

private Plane(final String plane) {
    this.plane= plane;
}

Plane(){ 
    plane=null; 
}


/**
 * toString method.
 * 
 * @return Value of this Enum as String.
 */
@Override
public String toString(){
   return plane;
}

/**
 * This method add support to compare Strings with the equalsIgnoreCase String method.
 * 
 * Replicated functionality of the equalsIgnorecase of the java.lang.String.class
 * 
 * @param value String to test.
 * @return True if equal otherwise false.
 */
public boolean equalsIgnoreCase(final String value){
    return plane.equalsIgnoreCase(value);
}

And then in main code:

然后在主代码中:

String airplane="BOEING_747";

if(Plane.BOEING_747.equalsIgnoreCase(airplane)){
     //code
}

回答by jyfar

You can compare a string to an enum item as follow,

您可以将字符串与枚举项进行比较,如下所示,

public class Main {

    enum IaaSProvider{
        aws,
        microsoft,
        google
    }

    public static void main(String[] args){

        IaaSProvider iaaSProvider = IaaSProvider.google;

        if("google".equals(iaaSProvider.toString())){
            System.out.println("The provider is google");
        }

    }
}

回答by Crushnik

My idea:

我的点子:

public enum SomeKindOfEnum{
    ENUM_NAME("initialValue");

    private String value;

    SomeKindOfEnum(String value){
        this.value = value;
    }

    public boolean equalValue(String passedValue){
        return this.value.equals(passedValue);
    }
}

And if u want to check Value u write:

如果你想检查值你写:

SomeKindOfEnum.ENUM_NAME.equalValue("initialValue")

Kinda looks nice for me :). Maybe somebody will find it useful.

对我来说有点好看:)。也许有人会发现它很有用。

回答by User2709

Doing an static import of the GestureTypes and then using the valuesOf() method could make it look much cleaner:

对 GestureTypes 进行静态导入,然后使用 valuesOf() 方法可以使它看起来更清晰:

enum GestureTypes{ROCK,PAPER,SCISSORS};

and

import static com.example.GestureTypes.*;
public class GestureFactory {

    public static Gesture getInstance(final String gesture) {
        if (ROCK == valueOf(gesture))
            //do somthing
        if (PAPER == valueOf(gesture))
            //do somthing
    }
}

回答by Ayaz Alifov

Define enum:

定义枚举:

public enum Gesture
{
    ROCK, PAPER, SCISSORS;
}

Define a method to check enumcontent:

定义一个方法来检查enum内容:

private boolean enumContainsValue(String value)
{
    for (Gesture gesture : Gesture.values())
    {
        if (gesture.name().equals(value))
        {
            return true;
        }
    }

    return false;
}

And use it:

并使用它:

String gestureString = "PAPER";

if (enumContainsValue(gestureString))
{
    Gesture gestureId = Gesture.valueOf("PAPER");

    switch (gestureId)
    {
        case ROCK:
            Log.i("TAG", "ROCK");
            break;

        case PAPER:
            Log.i("TAG", "PAPER");
            break;

        case SCISSORS:
            Log.i("TAG", "SCISSORS");
            break;
    }
}

回答by Srikanth

public class Main {

    enum Vehical{
        Car,
        Bus,
        Van
    }

    public static void main(String[] args){

      String vehicalType = "CAR";

        if(vehicalType.equals(Vehical.Car.name())){
            System.out.println("The provider is Car");
        }

     String vehical_Type = "BUS";

       if(vehical_Type.equals(Vehical.Bus.toString())){
            System.out.println("The provider is Bus");
        }


    }
}

回答by leopold

You can use equals().

您可以使用equals().

enum.equals(String)

enum.equals(String)