-1

I am supposed to create a simulation that does what pythons xrange does which is pick a start number, stop number, and step number in java. I am having trouble passing my constructor numbers to the Range class as it gives me an Exception in thread "main" java.lang.StackOverflowError. Everytime I step thru the program The Range constructor changes back to "Rane@365", I'm not sure what It means but my numbers I provide are gone.

 package com.company;

 public class Main {

public static void main(String[] args) {

    for (Integer num: new Range(1,10,2)) {
        System.out.println(num++);
    }

}

}

This is my Range class that uses interfaces Iterator and interface Iterable

package com.company;

 import java.util.Iterator;

public class Range implements Iterable<Integer>, Iterator<Integer> {

public Range(int start, int stop, int step){

    start = start;
    stop = stop;
    step = step;
}


public Iterator<Integer> iterator() {

    return this;
}


public boolean hasNext() {
    if (!this.hasNext()) {
        return true;
    } else
    return false;
}


public Integer next() {
    if (!hasNext()) {
        throw new IllegalStateException("No next");
    }
    return null;
}

public void remove() {

}

}

The stuff I have read uses ArrayLists, and I havent found anything on constructors and using loops for the Iterator and Iterable interfaces. I know the hasNext, next, remove are built in methods, where would the loop be? In the Main class or in one of the built in classes?

tkruse
  • 10,222
  • 7
  • 53
  • 80
Marcus
  • 5
  • 2
  • 1
    Why does it make sense for `Range` to be both `Iterable` and an `Iterator` simultaneously? – Jacob G. Mar 09 '20 at 00:02
  • 3
    Of course you get a stack overflow. Your `hasNext()` method calls itself and tries to return the opposite of its own return value. How is that supposed to work? – khelwood Mar 09 '20 at 00:03
  • https://stackoverflow.com/questions/28313726/java-8-intstream-for-an-int-range – OneCricketeer Mar 09 '20 at 00:19
  • For help on exceptions, it would be nice to post a few lines of the exception Trace. – tkruse Mar 09 '20 at 00:32
  • For a better solution, consider https://stackoverflow.com/questions/40358827/intstream-iterate-in-steps – tkruse Mar 09 '20 at 00:35
  • I don't know I've never worked with either iterable and iterator this is just the template I was given. – Marcus Mar 09 '20 at 00:41

1 Answers1

0

There is an infinite recursion here:

public boolean hasNext() {
    if (!this.hasNext()) {
      ...

This method calls itself every time, increasing the stack, until you get the StackOverflowException.

tkruse
  • 10,222
  • 7
  • 53
  • 80