I have,
String[] directions = {"North", "South", "West", "East"};
Not, I have a String s which is any one of those 4 String literals.
How do I get the index of s in directions?
I have,
String[] directions = {"North", "South", "West", "East"};
Not, I have a String s which is any one of those 4 String literals.
How do I get the index of s in directions?
A possible enum
public enum Direction {
NORTH("North"), SOUTH("South"), EAST("East"), WEST("West");
private String text;
private Direction(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
public class TestDirection {
public static void main(String[] args) {
System.out.printf("%10s: %-4s%n", "Direction", "Ordinal");
for (Direction dir : Direction.values()) {
System.out.printf("%10s: %-4d%n", dir.getText(), dir.ordinal());
}
}
}
Which prints out:
Direction: Ordinal
North: 0
South: 1
East: 2
West: 3
but again, the devil is in the details. As the enum API for this method states:
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.
You can achieve this using a for loop as well..
int i, index;
for i = 0; i < directions.lenght()-1; i++{
if(s.equals(directions[i]){
index = i;
break;
}
}
Try this simple snippet:
String[] directions = {"North", "South", "West", "East"};
int directionIndex = Arrays.asList(directions).indexOf("West");
This will give you the index of any string within the array or returns -1
if it is absent.
You can for example use
java.util.Arrays.asList(directions).indexOf(s)
A more general question with several excellent answers can be found here. The above solution is one of the answers listed there.