Reputation: 529
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.
Upvotes: 0
Views: 133
Reputation: 91049
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
}
}
}
Upvotes: 2
Reputation: 20112
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;
}
Upvotes: 1
Reputation: 837
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.
Upvotes: 1