Reputation: 86747
I'd like to create a mapping for ratings based on numbers. Each "original" number should get assigned a bunch of "target" numbers
Similar to this:
if (i = 2) return 3;
if (i = 3) return 5;
if (i = 4) return 7;
And so forth. How could I best write these sort of mappings, without having to repeatedly create ´if-return` statements?
Upvotes: 2
Views: 89
Reputation: 662
For your problem, there are two main solutions.
The first one is to take the three pairs of numbers that you give and put them into a Map. A map associates a key with a value, so you would put each pair into your map
HashMap<Integer, Integer> myMap = new HashMap();
myMap.put(myKey, myValue);
To get myValue from the map, you would access it through myMap.get(myKey)
The other way to do this is to note that the numbers that you give follow a function. 2x-1. You can create a function in the code to mimic this behavior
int myFunction(int value) {
return 2*value-1;
}
Just call this function and you will get the correct output. For example myFunction(3)
will return 5.
Upvotes: 2
Reputation: 1974
Map<Integer, Integer> mappings = new HashMap<Integer, Integer>();
mappings.put(2,3);
mappings.put(3,5);
mappings.put(4,7);
System.out.println(mappings.get(2));
System.out.println(mappings.get(3));
System.out.println(mappings.get(4));
Upvotes: 6