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

JavaEnums

Java Problem Overview


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: userPick is a String with values rock, paper, or scissors. I'm unable to use == to compare userPick to computerPick, which, as you can see below, is cast as type Gesture from my 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 rock not being equal to ROCK, or the String userPick not being able to match Gesture computerPick because 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...

Any hints?

Java Solutions


Solution 1 - Java

I'm gathering from your question that userPick is a String value. You can compare it like this:

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

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

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

Solution 2 - Java

You should declare toString() and valueOf() method in 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;
	}
}

Solution 3 - Java

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.

Solution 4 - Java

Define enum:

public enum Gesture
{
    ROCK, PAPER, SCISSORS;
}

Define a method to check enum content:

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(gestureString);

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

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

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

Solution 5 - Java

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");
        }
  

    }
}

Solution 6 - Java

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

Solution 7 - Java

This is my solution in java 8:

 public static Boolean isValidCity(String cityCode) {
        return Arrays.stream(CITY_ENUM.values())
                .map(CITY_ENUM::getCityCode)
                .anyMatch(cityCode::equals);
 }

Solution 8 - Java

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
}

Solution 9 - Java

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

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

Solution 10 - Java

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");
		}
		
	}
}

Solution 11 - Java

You can use equals().

enum.equals(String)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondwwilson66View Question on Stackoverflow
Solution 1 - JavaTed HoppView Answer on Stackoverflow
Solution 2 - JavakandarpView Answer on Stackoverflow
Solution 3 - JavaCrushnikView Answer on Stackoverflow
Solution 4 - JavaAyaz AlifovView Answer on Stackoverflow
Solution 5 - JavaSrikanthView Answer on Stackoverflow
Solution 6 - JavaoiyioView Answer on Stackoverflow
Solution 7 - JavaDavid Leonardo BernalView Answer on Stackoverflow
Solution 8 - JavaRami Del ToroView Answer on Stackoverflow
Solution 9 - JavaUser2709View Answer on Stackoverflow
Solution 10 - JavajyfarView Answer on Stackoverflow
Solution 11 - JavaleopoldView Answer on Stackoverflow