java – generate a vector with the first 100 prime numbers, then ask the user how many prime numbers he wants to see

Question:

As you read in the title, that is the problem as such, I am new to this and I am learning in a self-taught way, when looking for information I find similar things but nothing that comes close to solving the problem.

I don't know what I'm doing wrong or what I'm doing wrong, but I don't know how to correct it because it's giving me even numbers, not primes.

public static void main(String[] args) {
       int num=0,cprim=0,n;
       Scanner TC = new Scanner (System.in);
       int []tam = new int [100];
       while (cprim==tam.length){
           num+=1;
           if (num%2!=0){
               tam[cprim]=num++; 
               cprim++;
           }
       }
       System.out.println(" ¿Cuantos numeros primos desea ver? ");
       n= TC.nextInt();
       for (int i=0; i<n; i++){
           System.out.println( tam[i]+", ");
       }
       
    }
    
}

Answer:

validation if it is a prime number is wrong

if (num% 2! = 0)

What that validation does is check if it is not an even number.
I personally like to work with methods for each action to be performed; for your case I am going to create 3 methods: 1 to validate if it is a prime number, 1 to show the prime numbers and the main method.

I leave you the commented code

public class NumerosPrimos {
    static int[]vectorPrimos;
    
    public static void main(String[] args) {    
        int contador = 0; //Para validar la cantidad de números primos
        vectorPrimos=new int[100]; //vector para guardar los 100 números primos
        int i=2; //el primer número a evaluar si es primo
        
        Scanner sc=new Scanner(System.in);
        while(contador<100){            
            if(esPrimo(i)){
                vectorPrimos[contador]=i;
                contador++; //incrementamos por cada número primo
            }
            i++; //siguiente número a evaluar si es primo            
        } 
        
        System.out.println("Cuanto primos desea mostrar");
        mostrarPrimos(sc.nextInt()); 
    }
    
    public static boolean esPrimo(int numero){
        int contador = 2;
        boolean primo=true;
        while ((primo) && (contador!=numero)){
          if (numero % contador == 0) //validamos cuando no es primo
            primo = false;
          contador++;
        }
        return primo;
    }
    
    public static void mostrarPrimos(int cantidad){
        for(int i=0;i<cantidad;i++){
            System.out.print(vectorPrimos[i]+", "); //mostramos los primos
        }
    }
}

vectorPrimos is a class variable to access from any method of the class.

Observation
For this opportunity I have created the class variable and the methods in a static way so as not to have to create an object of the class NumerosPrimos but to call the methods directly.

Scroll to Top