Reputation: 2339
I have a method that takes in 2 ints method(int ii, int xx)
. I want to loop through a range of values but I cant think of a way to do it without hard coding each value.
When ii = 21, i want xx = 19 through 9 when ii = 20, i want xx = 18 through 12
so hard coded it would be:
method(21,19)
method(21,18)
...
method(21,10)
method(21,9)
method(20,18)
method(20,17)
...
method(20,13)
method(20,12)
this is what i have so far but it doesnt handle spcific cases like i dont want it to do method(4,19)
for(int ii = 9;ii<21;ii++){
for(int xx = 4;xx<19;xx++){
method(ii,xx);
}
}
Upvotes: 0
Views: 250
Reputation: 9584
As originally suggested by Edd, you'll want to use a map. I suggest creating a Range
class to represent an integer range for the xx
values, then you can build a map of Integer
--> Range
(ii --> xx):
static class Range {
public final int start;
public final int end;
public Range(int start, int end) {
this.start = start;
this.end = end;
}
}
static final Map<Integer,Range> RANGE_MAP = new HashMap<Integer,Range>();
static {
RANGE_MAP.put(21, new Range(9,19));
RANGE_MAP.put(20, new Range(12,18));
// ...
}
void calling_method() {
for(Entry<Integer,Range> entry : RANGE_MAP.entrySet()) {
int ii = entry.getKey();
Range r = entry.getValue();
for(int xx = r.start; xx <= r.end; xx++){
method(ii,xx);
}
}
}
void method(int ii, int xx) {
// do stuff
}
Upvotes: 2
Reputation: 8570
It is hard coded but a list in a map could do this for you:
private static final Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>(){{
put(21, new ArrayList<Integer>(){{
add(19);
add(18);
add(17);
...
}});
put(20, new ArrayList<Integer>(){{
add(18);
add(17);
...
}});
}};
Holding the map as static and final will mean you're not creating it each time you're using it.
Then you can loop through like so:
for(Integer ii : map.keySet()){
for(Integer xx : map.get(ii)){
method(ii,xx);
}
}
Upvotes: 0