Question

In: Computer Science

In Java, we typically iterate over a sequence of integers as follows: for (int i=0; i<10;...

In Java, we typically iterate over a sequence of integers as follows:

for (int i=0; i<10; i = i + 2) {
  ...
}

Suppose we use a version of Java that only supports for-each loops, i.e. it only allows you to iterate through the elements of an Iterable
In order to still be able to iterate over a sequence of numbers, you need to create such an Iterable, which we will call Range.

Modify the class Range.java so that it can be used as illustrated in TestRange.java (in the bottom).

The arguments passed to the constructor of Range are new Range(int start, int stop, int step).

  • start - the first integer produced
  • stop - iteration stops before stop is reached
  • step - the increment each time around the loop. Note that the step can be negative, as illustrated in the third example.

Range.java:

import java.util.Iterator;

/**
* A Range iterable that can be used to iterate over a sequence of integers
* (similar to Python's range function).
*/
public class Range implements Iterable<Integer> {
// you probably need some variables here and an inner class.
  
public Range(int start, int stop, int step) {
// change this
}

public Iterator<Integer> iterator() {
return null; // change this
}
  
}

TestRange.java

public class TestRange {

public static void main(String[] args) {
  
System.out.println("Range(1,8,1) should print 1 2 3 4 5 6 7");
for(Integer j : new Range(1,8,1)) {
System.out.print(j);
System.out.print(" ");
}
System.out.println("\n");

System.out.println("Range(1,8,2) should print 1 3 5 7");
for(Integer j : new Range(1,8,2)) {
System.out.print(j);
System.out.print(" ");
}
System.out.println("\n");

System.out.println("Range(8,0,-1) should print 8 7 6 5 4 3 2 1");
for(Integer j : new Range(8,0,-1)) {
System.out.print(j);
System.out.print(" ");
}
System.out.println("\n");
}
  
}

Solutions

Expert Solution

//Java code

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * A Range iterable that can be used to iterate over a sequence of integers
 * (similar to Python's range function).
 */
public class Range implements Iterable<Integer> {
// you probably need some variables here and an inner class.
    private int start, stop,step;

    public Range(int start, int stop, int step) {
        this.start =start;
        this.stop =stop;
        this.step = step;
    }

    public Iterator<Integer> iterator() {
        return new MyRangeIterator();
    }
    //inner class
    private class MyRangeIterator implements Iterator<Integer>
    {
        private int position;
        public MyRangeIterator()
        {
            this.position = Range.this.start;
        }
        /**
         * Returns {@code true} if the iteration has more elements.
         * (In other words, returns {@code true} if {@link #next} would
         * return an element rather than throwing an exception.)
         *
         * @return {@code true} if the iteration has more elements
         */
        @Override
        public boolean hasNext() {
            if(Range.this.step>0)
            return this.position <Range.this.stop;
            else
                return this.position >Range.this.stop;
        }

        /**
         * Returns the next element in the iteration.
         *
         * @return the next element in the iteration
         * @throws NoSuchElementException if the iteration has no more elements
         */
        @Override
        public Integer next() {
            if(this.hasNext())
            {
                int current = position;
                position = position +Range.this.step;
                return current;
            }
            throw new NoSuchElementException();
        }
    }
}

//==========================================

public class TestRange {

    public static void main(String[] args) {

        System.out.println("Range(1,8,1) should print 1 2 3 4 5 6 7");
        for(Integer j : new Range(1,8,1)) {
            System.out.print(j);
            System.out.print(" ");
        }
        System.out.println("\n");

        System.out.println("Range(1,8,2) should print 1 3 5 7");
        for(Integer j : new Range(1,8,2)) {
            System.out.print(j);
            System.out.print(" ");
        }
        System.out.println("\n");

        System.out.println("Range(8,0,-1) should print 8 7 6 5 4 3 2 1");
        for(Integer j : new Range(8,0,-1)) {
            System.out.print(j);
            System.out.print(" ");
        }
        System.out.println("\n");
    }

}

//Output

//If you need any help regarding this solution .......... please leave a comment ........ thanks


Related Solutions

#include <iostream> using namespace std; int main() { int even=0,odd=0,sum=0,sum2=0,largest,smallest; int num,i; for ( i=1; i<=10;...
#include <iostream> using namespace std; int main() { int even=0,odd=0,sum=0,sum2=0,largest,smallest; int num,i; for ( i=1; i<=10; i++){ cout << " Enter " << i << " number: "; cin >> num; if ( num%2==0){ even++; sum+=num; } else { odd++; sum2+=num; if(num>largest){ largest = num; } if(num<largest) { smallest = num; } } cout << " The sum of even number is : " << sum << endl; cout << " The total-count of even number is : " <<...
How many times will the following while loop iterate? int i = 1; while (i <...
How many times will the following while loop iterate? int i = 1; while (i < 5) {     i = i + 1;     System.out.println(“Hello!”); } Group of answer choices 4 0 5 It will iterate infinitely
In Java: int[] A = new int[2]; A[0] = 0; A[1] = 2; f(A[0],A[A[0]]); void f(int...
In Java: int[] A = new int[2]; A[0] = 0; A[1] = 2; f(A[0],A[A[0]]); void f(int x, int y) { x = 1; y = 3; } For each of the following parameter-passing methods, saw what the final values in the array A would be, after the call to f. (There may be more than one correct answer.) a. By value. b. By reference. c. By value-result.
int f2 (int n) j = 0; while (j <n) {for (int i = 0; i...
int f2 (int n) j = 0; while (j <n) {for (int i = 0; i <n; ++ i) {cout << "j =" + j; j = j + 5; }}
A sequence of integers x1,x2,...,xn is unimodal if for some 1 ≤ i ≤ n we...
A sequence of integers x1,x2,...,xn is unimodal if for some 1 ≤ i ≤ n we have x1 < x2 < ... < xi and xi > xi+1 > ... > xn. Find the maximum element in a unimodal sequence of integers x1, x2, . . . , xn. The running time should be O(log n). Show that your algorithm meets the bound.
14. How many times does "#" print? for(int i = 0; i < 10; ++i) {...
14. How many times does "#" print? for(int i = 0; i < 10; ++i) { if(i == 2 || i==4 || i==6) { continue; } cout << "#"; }
(C++)Change the following loop to a while loop: int i; for (i=0; i<10; i++) {    ...
(C++)Change the following loop to a while loop: int i; for (i=0; i<10; i++) {     cout<<i<<endl; }
Java Program Sequential Search You are given a sequence of n integers S and a sequence...
Java Program Sequential Search You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S. Do not use any import sort packages. Input: In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given. Output:...
I need Java Code for both questions....thx Question 1 Consider the sequence of integers defined as...
I need Java Code for both questions....thx Question 1 Consider the sequence of integers defined as follows: The first term is any positive integer. For each term n in the sequence, the next term is computed like this: If n is even, the next term is n/2. If n is odd, the next term is 3n+1. Stop once the sequence reaches 1. Here are a few examples of this sequence for different values of the first term: • 8,4,2,1 •...
public void printQueue(DoublyLinkedQueue<Integer> Q){ int len = Q.size(); int k = 0; for (int i=0; i...
public void printQueue(DoublyLinkedQueue<Integer> Q){ int len = Q.size(); int k = 0; for (int i=0; i < len; ++i){ k = Q.dequeue(); Q.enqueue(k);    System.out.println(Q.dequeue()); } } What is the complexity of this code? Select one: a. O(N), N = k b. Q(1) c. Q(N2), N = Q.size() d. O(M), M = Q.size() e. None of the alternatives is correct. which one?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT