// SI 413 Fall 2011 // Homework for Class 23 import java.util.Iterator; public class Primes { public static void main(String[] args) { PGen pg = new PGen(); Iterator<Integer> iter = pg.iterator(); while (iter.hasNext()) { int p = iter.next(); if (p > 100) break; else System.out.println(p); } // RE-WRITE THAT WHILE LOOP AS A FOR-EACH! } } class PIter implements Iterator<Integer> { // YOU WILL HAVE TO ADD SOME PRIVATE FIELD(S) TO KEEP TRACK // OF THE STATE OF THE ITERATOR! // This helper method determines whether a number is prime. // You're welcome. boolean isprime(int n) { for (int i = 2; i*i <= n; ++i) if (n % i == 0) return false; return true; } public Integer next() { // Should return the next prime number, starting from 2. // YOU HAVE TO WRITE THIS. } public boolean hasNext() { // Are there more primes???? } // This is part of the interface but makes no sense for us. public void remove() { throw new UnsupportedOperationException(); } } // The Iterable interface means we can use this in a for-each loop class PGen implements Iterable<Integer> { public Iterator<Integer> iterator() { return new PIter(); } }