Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package pgdp.iter;
- import java.util.ArrayList;
- import java.util.Iterator;
- public class Range implements Iterable<Integer>{
- private final int begin;
- private final int end;
- private final int stride;
- public Range(int begin, int end, int stride) {
- this.begin = begin;
- this.end = end;
- this.stride = stride;
- if (stride <= 0) {
- Util.badArgument("Anzahl der Schritte soll größer 0 sein");
- }
- }
- public Range(int begin, int end) {
- this.begin = begin;
- this.end = end;
- stride = 1;
- }
- public Iterator<Integer> iterator() {
- ArrayList<Integer> list = new ArrayList<Integer>();
- if (begin == end)
- list.add(begin);
- if (begin < end) {
- list.add(begin);
- int addition = begin + stride;
- while (addition <= end) {
- list.add(addition);
- addition += stride;
- }
- } else {
- list.add(begin);
- int subtraction = begin - stride;
- while (subtraction >= end) {
- list.add(subtraction);
- subtraction -= stride;
- }
- }
- Iterator<Integer> iter = list.iterator();
- while (iter.hasNext())
- System.out.print(iter.next() + ", ");
- return iter;
- }
- public static void main(String[] args) {
- Range range = new Range(14, 24, 3);
- Iterator<Integer> iter = range.iterator();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement