将String与枚举值进行比较的正确方法是什么? [英] What's the proper way to compare a String to an enum value?

查看:134
本文介绍了将String与枚举值进行比较的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作业:Rock Paper Scissors游戏。

Homework: Rock Paper Scissors game.

我创建了一个枚举:

      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.

嗯...这个将会澄清: userPick 是一个 String ,值为 rock paper 剪刀。我无法使用 == userPick computerPick ,正如你可以看到的,从我的枚举中转换为类型 Gesture

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

我猜想有一个问题与 rock 不等于 ROCK String userPick 无法匹配 Gesture computerPick ,因为后者不是 String 。但是,我无法在我的教科书或Oracle的Java教程中找到类似情况的例子,所以我不知道如何解决问题...

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

任何提示?

推荐答案

我从您的问题收集 userPick 是一个 String 值。你可以这样比较:

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

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

除此之外,如果您确保计算机始终是 1 2 3 (没有别的),您可以将它转换为手势枚举:

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

这篇关于将String与枚举值进行比较的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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