The mistake is that you doesn't initialize val
, so it will start at 0
(the default value).
In your second example, you will return val += step;
, with val = 0
and step = 2
, so it will start at 2
and continue from there.
In your third example, a = 10
, b = 1
, step = -1
and val = 0
, so you will not enter in
if (step < 0 && val > a)
because val < a
, and you will not enter in
else if (step > 0 && val < b)
because step < 0
.
EDIT:
In the edited post, you should modify the next()
method to return val
, and only increase it after :
@Override
public Integer next() {
int ret = val;
val += step;
return val;
}
You should also modify the conditions in the hasNext()
:
@Override
public boolean hasNext() {
if (step < 0 && val >= a)
return true;
else if (step > 0 && val <= b)
return true;
return false;
}
To make you fourth test work, you will have to change the by()
method to invert a
and b
if needed:
public Incrementer by(int step) {
if ((this.step<0)!=(step<0) && this.val==this.a)
this.val = this.b;
else if ((this.step<0)!=(step<0) && this.val==this.b)
this.val = this.a;
else if (this.val!=this.a && this.val!=this.b) {
this.val -= this.step;
this.val += step;
}
this.step = step;
return this;
}
You can also test the inverse case:
for(int k : in(10, 1).by(1)) System.out.print(k + " ");
Here is the complete code:
public class Incrementer implements Iterable<Integer> {
int val, step, a, b;
private Incrementer(int a, int b, int step) {
this.step = step;
this.a = a;
this.b = b;
if (step > 0)
val = a;
else
val = b;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
@Override
public boolean hasNext() {
if (step < 0 && val >= a)
return true;
else if (step > 0 && val <= b)
return true;
return false;
}
@Override
public Integer next() {
int ret = val;
val += step;
return ret;
}
@Override
public void remove() {
}
};
}
public static Incrementer in(int a, int b) {
///tu zmieniamy tresc dla ostatniego przypadku
if (a < b)
return new Incrementer(a, b, 1);
else
return new Incrementer(b, a, -1);
}
public Incrementer by(int step) {
if ((this.step<0)!=(step<0) && this.val==this.a)
this.val = this.b;
else if ((this.step<0)!=(step<0) && this.val==this.b)
this.val = this.a;
else if (this.val!=this.a && this.val!=this.b) {
this.val -= this.step;
this.val += step;
}
this.step = step;
return this;
}
}