【问题标题】:So I want to use specific chars to move an obect, via an enum in java所以我想通过java中的枚举使用特定的字符来移动对象
【发布时间】:2021-12-05 07:52:03
【问题描述】:

因此,我被分配了制作一个程序以在 java 中围绕字符串映射移动对象的任务。我被要求通过文件资源使用具有特定字符的枚举来通过 ObjCommand 枚举命令移动。
就基础知识而言,这就是我所掌握的……但是我一直在旋转我的轮子来尝试不同的东西,现在我都糊涂了。 所以这里-

  public enum ObjCommand {

FORWARD (F),
TURN_LEFT(L),
TURN_RIGHT(R),

(其他命令...);

public char directionKey;


private ObjCommand(char directionKey){
    this.directionKey = directionKey;     
}
//public char getDirectionKey() {
 //  return DirectionKey
public final char getDirectionKey(char directionKey){
    return directionKey;
} 

....我正在尝试使用不同的方法,例如 toString 等,我知道我会需要这些方法,但是字符(F,L 等)似乎不想注册为变量现在我完全糊涂了。

我还在学习,如果有任何帮助,我们将不胜感激 :)
我确定我没有正确解释自己,所以这里是这个特定部分的 uml,以防它可以增加我在这里尝试做的任何清晰度:

enum ObjCommand <<enumeration>>
+ FORWARD : F
+ TURN_LEFT : L
+ TURN_RIGHT : R
(etc. other moves by key entry) then:
- ObjCommand(directionKey : char)
+ getDirectionKey() : char

我感谢任何花时间研究这个并帮助我们解决问题的人。这部分让我有点发疯:)

【问题讨论】:

    标签: java enums char command tostring


    【解决方案1】:

    您的枚举可能如下所示:

    public enum ObjCommand {
    
        FORWARD('F');
        
        private final char key;
        
        private ObjCommand(char key) {
            this.key = key;
        }
        
        public char getDirectionKey() {
            return key;
        }
    }
    

    使用getDirectionKey,您可以取回您的密钥。

    【讨论】:

      【解决方案2】:

      就开始使用枚举而言,您可以通过枚举名称访问它们,如下所示:

      ObjCommand.TURN_LEFT
      

      如果你想通过单个字符串访问,你可以写一个静态函数,如下所示:

      static ObjCommand getFromChar(char c) {
          switch (c) {
          case 'F':
              return ObjCommand.FORWARD;
          case 'L':
              return ObjCommand.TURN_LEFT;
          case 'R':
              return ObjCommand.TURN_RIGHT;
          default:
              throw new IllegalArgumentException("Invalid command character "+ c);
          }
      }
      
      

      另外,关于getDirectionKey,您当前的版本只返回传入的任何值,因此它与枚举值无关。您真正想要的可能是 final 字段 directionKey 和返回其值的 getter:

      public char getDirectionKey() {
          return this.directionKey;
      }
      

      【讨论】:

      • 哇,感谢大家的快速帮助。非常感谢,我肯定对现在需要发生的事情更有信心。
      【解决方案3】:

      也许您可以检查一下并与您的代码进行比较:

      https://www.baeldung.com/java-enum-values

      第二个:

      你的字符不应该用引号引起来吗?

      FORWARD ('F'),
      

      getter 不应该采用输入参数。

      【讨论】:

        猜你喜欢
        • 2011-09-07
        • 2012-05-12
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多