How to write code that performs actions based on what type
Please bear with me as I am struggling to explain this issue. So let's say I have a custom type called "UserType" and that this type has 4 values: North, South, East, and West.
public enum UserType {
NORTH, SOUTH, EAST, WEST
}
Then I want to write a method statement in another class that will increment the value of two variables based on the type. For example,
public class direction {
private int peopleWhoGoNorth;
private int peopleWhoGoSouth;
therefore peopleWhoGoNorth has to keep track of the number of people who go north each time the following method is called:
public void whichWay(UserType type) {
}
I'm wondering how I would create a statement between the parentheses that basically says, if type North, add 1 to peopleWhoGoNorth, and if type is South, add 1 to peopleWhoGoSouth. I assume the if / else statement should do this, but I'm not sure how the syntax will work. Is the following OK?
public void whichWay (UserType type){
if (UserType = NORTH){peopleWhoGoNorth = peopleWhoGoNorth + 1);
if (UserType = SOUTH){peopleWhoGoSouth = peopleWhoGoSouth + 1);
}
Please let me know if there is a way to explain the question.
source to share
You can just compare yours type
with the types you want to test.
public void whichWay(UserType type) {
if (type == UserType.NORTH) {
//Execute code
}
//Other types analog
}
or you can use a switch statement:
public void whichWay(UserType type) {
switch (type) {
case NORTH:
//Execute code
break;
//Other types analog
default:
}
}
source to share
switch
and if-else
, but you can also use Map
to keep a counter of those who left in a given direction.
public enum UserType {
NORTH, SOUTH, EAST, WEST
}
public class Example{
private final Map<UserType,Integer> typeMap = new HashMap<>();
public void whichWay(UserType type){
int val = typeMap.getOrDefault(type,0);
typeMap.put(type,val++);
}
}
Of course, you will need to add methods to get these values to make this useful.
source to share
One option would be to use EnumMap :
private final EnumMap<UserType, Integer> counter = new EnumMap<> (UserType.class);
{
for (UserType u : UserType.values()) counter.put(u, 0);
}
public void whichWay (UserType type){
counter.put(type, counter.get(type) + 1);
}
Or with Java 8:
private final EnumMap<UserType, Integer> counter = new EnumMap<> (UserType.class);
public void whichWay (UserType type){
counter.compute(type, (u, i) -> i == null ? 0 : i + 1);
}
(Note: this is not thread safe)
source to share