Use the Next () method of the Iterator interface

0

I have been trying for a few hours now to implement the next () method of the Iterator interface, with the aim of returning the next prime number

The constructor receives an argument that specifies the limit of the maximum prime number. For example, Prime Iterator (100) creates an object that iterates prime numbers less than or equal to 100.

@Override
public Integer next() {

    Integer contador = limite;
    Integer num = 0;
for(int i=0;i<contador && esPrimo(num)==false;i++)
        num+=i;
        return num;

}

This is one of the codes that has occurred to me but I only get the value that has num at the beginning, that is, zero. Thanks for the answers

    
asked by Piñero11 26.03.2018 в 13:40
source

2 answers

0

It always returns 0 because you always start looking from 0, you have to start looking at the last cousin you have obtained.

To do this, you have to declare a global variable to save the last cousin that you have returned and thus continue calculating the following ones from this one.

public int ultimoPrimo = 0;

@Override
public Integer next() {
    int num=0;
    int contador = limite;
    for(int i=ultimoPrimo+1;i<contador && esPrimo(i)==false;i++) //Ponemos ultimoPrimo +1 porque sino nos va a devolver el mismo
        num = num+1;

    return num;
}

When you call the function you will have to call it like this:

ultimoPrimo = next();
    
answered by 26.03.2018 в 13:49
0

Iterator Definition: Used to browse collections of objects. A good one to use Iterator, it would be this.

  

1) Prime numbers from 1 to 100

Integer[] primos = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
  

2) We create a list and add non-cousins

List lista = Arrays.asList(primos);
  

3) We create iterator

Iterator i = lista.iterator();
  

4) We go through the list

while(i.hasNext()){ //Devuelve true si la iteración tiene más elementos
      System.out.print(i.next()+" ");
}

Greetings !!

    
answered by 26.03.2018 в 18:20