用于操作Enum案例的Java Switch语句

时间:2011-06-24 16:26:49

标签: java switch-statement

我有一个java文件的以下部分:

Integer x; Integer y; Face facing;

enum Rotate { Clockwise, Anticlockwise };

enum Face { East, North, West, South };

并且无法弄清楚如何实现一个函数来更改对象的面(即对象面向的方向)。

该功能如下开始

private void rotateIt(Rotate rotateIt) {
    {

我已经开始使用如下的switch语句(下面的文字在上面的大括号内):

switch (facing)
case North  : ...?;
case West   : ...?;
case East   : ...?;
case South  : ...?;

我想使用Clockwise枚举将其从East转换为South等,并Anticlockwise执行相反的IYGWIM。

5 个答案:

答案 0 :(得分:4)

switch (facing) {
  case North  : facing=rotateIt==Rotate.Clockwise?Face.East:Face.West; break;
  case West   : facing=rotateIt==Rotate.Clockwise?Face.North:Face.South; break;
  case East   : facing=rotateIt==Rotate.Clockwise?Face.South:Face.North; break;
  case South  : facing=rotateIt==Rotate.Clockwise?Face.West:Face.East; break;
}

我应该追溯你的成绩的很大一部分!

答案 1 :(得分:2)

我会根据面部方向实现旋转:

 enum RotationDirection { Clockwise, CounterClockwise };
 enum Face {
    East, North, West, South ;

    Face rotate(RotationDirection direction ) {
        int tick  = (direction == RotationDirection.Clockwise)?-1:1;
        int index = this.ordinal()+tick ;
        int length = Face.values().length-1;
        if (index <0) index = length;
        if (index >length) index = 0;
        return Face.values()[index];
    }

然后你可以做以下事情:

 Face face = Face.North;
 face.rotate(RotationDirection.Clockwise); // East
 face.rotate(RotationDirection.CounterClockwise); //West 

此代码使用Enums很少使用的'ordinal'属性。因此,要求值处于逻辑转动顺序,例如(东,北,西,南)

答案 2 :(得分:1)

另一个选择是使用枚举来完成工作。

enum Face { 
    North, East, South, West; // must be clockwise order.
}

enum Rotate { 
    private static final Face[] FACES = Face.values();
    Clockwise {
        public Face rotate(Face face) {
            return FACES[(ordinal()+1)%FACES.length];
        }
    }, 
    Anticlockwise {
        public Face rotate(Face face) {
            return FACES[(ordinal()+FACES.length-1)%FACES.length];
        }
    }
    public abstract Face rotate(Face face);
};

facing = rotateIt.rotate(facing);

答案 3 :(得分:0)

case North:
{
  if(rotateIt == Rotate.Clockwise)
    facing = Face.EAST
  else
    facing = Face.WEST
  break;
}

依旧......

答案 4 :(得分:0)

你开始很好。以下是关于枚举操作的更完整版本:

public void RotateIt(Rotate toRotate, Face facing) {

switch (facing) {
    case North:
        // Include code to rotate from north
        break;
    case West:
        // Include code to rotate from west
        break;
    case East:
        // Include code to rotate from east
        break;
    default: // South
        // Include code to rotate from south
        break;
}

}

当然,此代码可以进行优化,但它可以让您了解如何在enums语句中处理switch