简体   繁体   English

我如何编写一种方法,该方法将遍历枚举输入次数?

[英]How do i write a method that will loop through an enum an inputted number of times?

I have this enum: 我有这个枚举:

public enum Direction {
    NORTH, WEST, SOUTH, EAST;
}

and this method: 和这个方法:

public void turn(int n){
    for (int i = 0; i < n; i++){
        //Change compass direction n times
    }
}

And what I need to do is change the direction by 90 degrees counter clockwise an inputted "n" number of times. 我需要做的是将方向逆时针旋转90度,输入次数为“ n”次。 I set up the enum so that it would be in the correct order, I just am not sure how I could make it so the current value compassDirection can be changed in terms of iterating through the enum "n" times. 我将枚举设置为正确的顺序,但我不确定如何做到这一点,以便可以通过迭代枚举“ n”次来更改当前值的罗盘方向。

If I understand correctly, you want to iterate over the enum members. 如果我理解正确,则需要遍历enum成员。

In order to do so, every enum has a .values() method which returns an array with all valid values in the defined order. 为了做到这一点,每个enum都有一个.values()方法,该方法以定义的顺序返回具有所有有效值的数组。

So with 所以用

public void turn(int n){
    for (int i = 0; i < n; i++){
        for (Direction direction : Direction.values()) {
            // Do something with direction
        }
    }
}

you basically achieve what you want. 您基本上可以实现您想要的。


Edit: After your clarification, I think you are rather after 编辑:澄清之后,我认为您宁可

public void turn(int n){
    Direction[] directions = Direction.values()
    for (int i = 0; i < n; i++) {
        int direction_index = i % directions.length;
        Direction direction = directions[direction_index];
        // Do something with direction
    }
}

or 要么

public void turn(int n){
    int i = 0;
    while (true) {
        for (Direction direction : Direction.values()) {
            if (i==n) return;
            i++
            // Do something with direction
        }
    }
}

I think you don't need an iteration here. 我认为您不需要在此进行迭代。 You can achieve turning like this: 您可以像这样实现转弯:

public Direction turn(Direction initial, int turns)
{
    Direction[] dirs = Direction.values();
    return dirs[(initial.ordinal()+turns) % dirs.length];
}

In this code you are getting current element's index in enum, and based on number of turns you get the index of the result. 在此代码中,您将获取枚举中当前元素的索引,并根据转数获得结果的索引。 And by the result index you can gen an enum value. 通过结果索引,您可以生成一个枚举值。

public static void main(String[] args) {
    turn(6);
}

public static Direction turn(int n){
    Direction result = null;
    Direction[] values = Direction.values();
    for(int i = 0; i < n; i++){
        result = values[i % values.length];
        System.out.println(i + " " + result);
    }
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM