Я должен реализовать класс Incrementer
, и он должен реализовать Iterable
.Итератор возвращает неправильные целочисленные значения
Вывод должен быть:
1 2 3 4 5 6 7 8 9 10
1 3 5 7 9
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
1 2 3 4 6 8 10
1 2 3 4 5 6 7 8 6 4 2
10 9 8 7 6 5 6 7 8 9 10
я получаю:
2 3 4 5 6 7 8 9 10
3 5 7 9 11
9 8 7 6 5 4 3 2 1
2 3 4 6 8 10
2 3 4 5 6 7 8
9 8 7 6 5 6 7 8 9 10
Мой Incrementer
класс выглядит следующим образом:
package in;
import java.util.Iterator;
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() {
return val += step;
}
@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) {
this.step = step;
if (this.step < 0 && this.a < this.b || this.step > 0 && this.a > this.b) {
int tmp = this.a;
this.a = this.b;
this.b = tmp;
}
return this;
}
}
и в Testcode:
package in;
import static in.Incrementer.*;
public class Test {
public static void main(String[] args) {
for(int k : in(1, 10)) System.out.print(k + " ");
System.out.println();
for(int k : in(1, 10).by(2)) System.out.print(k + " ");
System.out.println();
for(int k : in(10, 1)) System.out.print(k + " ");
System.out.println();
for(int k : in(1, 10).by(-1)) System.out.print(k + " ");
System.out.println();
Incrementer inc;
for (int i : inc = in(1,10)) {
if (i == 4) inc.by(2);
System.out.print(i + " ");
}
System.out.println();
for (int i : inc = in(1,10)) {
if (i == 8) inc.by(-2);
System.out.print(i + " ");
}
System.out.println();
for(int k : inc = in(10, 1)) {
if (k == 5) inc.by(1);
System.out.print(k + " ");
}
}
}
Я не знаю, где я ошибся.
Спасибо Я отредактировал OP. Взгляни, пожалуйста. Еще раз спасибо. – Yoda
Спасибо, я снова отредактировал код, как вы сказали. Но, к сожалению, результат такой же, как и в исходном сообщении. Взгляни, пожалуйста. О, отредактирован op – Yoda
@Yoda Отредактирован мой ответ. –