简体   繁体   中英

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

If I understand correctly, you want to iterate over the enum members.

In order to do so, every enum has a .values() method which returns an array with all valid values in the defined order.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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