LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 6

A Range class that implements Iterable in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write a Range(start, end, step) class that implements Iterable<Integer> (supporting negative steps) so it works in for-each loops; print several ranges and a sum.

Solution
Main.java
import java.util.Iterator;
import java.util.NoSuchElementException;

class Range implements Iterable<Integer> {
    private final int start, end, step;
    Range(int start, int end, int step) {
        if (step == 0) throw new IllegalArgumentException("step 0");
        this.start = start; this.end = end; this.step = step;
    }

    @Override public Iterator<Integer> iterator() {
        return new Iterator<>() {
            private int cur = start;
            public boolean hasNext() { return step > 0 ? cur < end : cur > end; }
            public Integer next() {
                if (!hasNext()) throw new NoSuchElementException();
                int v = cur;
                cur += step;
                return v;
            }
        };
    }
}

public class Main {
    static String show(Range r) {
        StringBuilder sb = new StringBuilder();
        for (int v : r) sb.append(v).append(' ');
        return sb.toString().trim();
    }

    public static void main(String[] args) {
        System.out.println(show(new Range(0, 10, 3)));
        System.out.println(show(new Range(10, 0, -4)));
        System.out.println("[" + show(new Range(5, 5, 1)) + "]");
        int sum = 0;
        for (int v : new Range(1, 101, 1)) sum += v;
        System.out.println(sum);
    }
}

Output Verified by compiling and running

0 3 6 9
10 6 2
[]
5050

Implementing Iterable is all a class needs to work with the enhanced for loop.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links