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 : " <<...
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.
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
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; }}
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; }
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?
CS 211 Q.Adding BIG Integers In C++ an int is in the range 0 to 65535....
CS 211 Q.Adding BIG Integers In C++ an int is in the range 0 to 65535. But what if we need to add larger integers? Say we want to compute the sum 2345566777844567+ 9999988777765768009998. Your task in this assignment is to make this happen. Write a function string add(string a, string b)
JAVA JAVA JAVA . I need to convert a string input to int array, for example...
JAVA JAVA JAVA . I need to convert a string input to int array, for example if user enters 12 / 27 / 2020 , I want to store each value in a separate array and add them afterwards.
#include <stdio.h> int main() { int i, j; printf("Enter two positive integers: "); scanf("%d%d", &i, &j);...
#include <stdio.h> int main() { int i, j; printf("Enter two positive integers: "); scanf("%d%d", &i, &j); // need to validate both being positive while (i != j) { i > j ? (i -= j) : (j -= i); } printf("GCD: %d\n", i); return 0; } The above code returns a GCD from two numbers entered. Use the above program to design a C program to compute of integer coefficients a and b such that gcd(i, j) = a xi...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT