(25 pts) This page is all one class import java.util.Iterator; public class MySt
ID: 3873739 • Letter: #
Question
(25 pts) This page is all one class import java.util.Iterator; public class MyStepper implements Iterator int state0; int step; //WRITE A CONSTRUCTOR // THIS MAIN PRINTS: / 5 10 15 20 25 30 35 40 45 50 11 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 public static void main(Stringt] args) for (Iterator sIter new MyStepper (5) sIter.hasNext System.out.print(""+sIter.next System.out.println for (Iterator sIter new MyStepper (3 sIter.hasNext i) System.out print(" "+sIter.next ) System.out.printin //write any other code this class needs to make main) work as shown.Explanation / Answer
The constructor for MyStepper() is given below-
public MyStepper(int step)
{
this.step = step;
}
Apart from the constructor, we need to implement 2 more methods from Iterator interface for the main() to work. The 2 methods are hasNext() and next() given below. Notice from the output of main, that the output stops once the number is more than 50. So hasNext() checks for that condition.
public boolean hasNext() {
return state < 50;
}
public Integer next() {
state = state + step;
return state;
}
The complete code is given below with constructor and other methods along with output. Please don't forget to rate the answer if it helped. thank you.
import java.util.Iterator;
public class MyStepper implements Iterator<Integer>{
int state = 0;
int step ;
public MyStepper(int step)
{
this.step = step;
}
@Override
public boolean hasNext() {
return state < 50;
}
@Override
public Integer next() {
state = state + step;
return state;
}
public static void main(String[] args) {
for(Iterator<Integer> sIter = new MyStepper(5); sIter.hasNext(); ){
System.out.print(" " + sIter.next());
}
System.out.println();
for(Iterator<Integer> sIter = new MyStepper(3); sIter.hasNext(); ){
System.out.print(" " + sIter.next());
}
System.out.println();
}
}
output
5 10 15 20 25 30 35 40 45 50
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.