Problem print in cycle for

4

I want the program to ask me how many numbers I want to enter and then show me if each number I entered is a cousin or no cousin, but instead I am getting a number and immediately tell me if it is a cousin or not, then the next number and it tells me if it is a cousin or not, and so, with the n numbers that I decide to enter.

My code:

import java.util.Scanner;
public class Main {

    public static void main(String[] args){
        Scanner leer=new Scanner(System.in);
        int N, i, z;
        N=leer.nextInt();
        for(i=1;i<=N;i++){
            z=leer.nextInt();

            if(z%2!=0||z==2){
                System.out.println("primo");
            }
            else{
                System.out.println("no primo");
            }
        }
    }
 }

And this is what I'm getting (vertically)

  

3
  2
  cousin
  1
  no cousin
  5
  cousin

When I want to, it's

  

3
  2
  1
  5
  cousin no cousin cousin

    
asked by Alejandro Bedoya 30.08.2018 в 07:45
source

2 answers

3

The problem you currently have is that you read the number in the loop for{} and immediately calculate its result, which is why your program does not work as expected.

I pass some modifications that may be useful and I'll explain a little:

import java.util.Scanner;

public class Main {

    private static boolean isPrimo(int numero) {
        // Función para indicar si un número es primo o no, tu manera de detectarlo
        // anteriormente también era erronea. esto lo puedes modificar como mejor veas.
        int contador = 0;
        for (int i = 1; i <= numero; i++) {
            if ((numero % i) == 0) {
                contador++;
            }
        }
        if (contador <= 2) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        Scanner leer = new Scanner(System.in);

        // Primero se pide el número total de elementos que queremos evaluar para saber
        // si son primos o no.

        System.out.println("Inserte el total de números a evaluar: ");
        int totalNum = leer.nextInt();

        // Una vez que tienes el total de números, pasas a pedir que te inserten cada
        // uno de los mismos, por ejemplo si el total son 3, el usuario tiene que
        // introducir 3 números para ser evaluados. Estos números necesitas guardarlos
        // en un array para quue luego los puedas evaluar todos de golpe y no uno a uno
        // como es el caso que te ocurre actualmente.
        System.out.println("Ahora debe introducir un total de " + totalNum + " numeros: ");
        int[] numerosInsertado = new int[totalNum]; // Donde almacenarémos los números a evaluar
        for (int i = 0; i < totalNum; i++) {
            numerosInsertado[i] = leer.nextInt(); // Se guardan en la posición correspondiente.
        }

        // Una vez que ya tenemos todos los números insertados, pasamos a evaluarlos y
        // mostrar el resultado correspondiente a cada uno.
        System.out.println("El resultado es el siguiente: ");
        for (int i = 0; i < totalNum; i++) {
            if (isPrimo(numerosInsertado[i])) {
                System.out.print(numerosInsertado[i] + " = primo; ");
            } else {
                System.out.println(numerosInsertado[i] + " = no primo; ");
            }
        }
    }

}
    
answered by 30.08.2018 / 09:09
source
1

This gives the result you are looking for:

public static void main(String[] args)
{
    Scanner scanner = new Scanner(System.in); // Crear scanner
    System.out.println("¿Cuantos numeros?"); // Preguntar cuantos numeros
    int numbersToInput = scanner.nextInt(); // Guardar la cantidad de numeros
    boolean[] results = new boolean[numbersToInput]; // Crear un array para guardar los resultados de que numeros son primos

    for (int i = 0; i < numbersToInput; i++)
    {
        int newNumber = scanner.nextInt(); // Guardamos el numero que el usuario envia para comprobar si es primo

        // Si el numero es primo, añadimos "true" al array
        if (esNumeroPrimo(newNumber))
            results[i] = true;
        // Si el numero no es primo, añadimos "false" al array
        else
            results[i] = false;
    }

    // Hacemos un loop en el array de boolean, escribimos "primo" si es "true", "no primo" si no lo es
    for (boolean b : results)
        if (b)
            System.out.print("primo ");
        else
            System.out.print("no primo ");
    scanner.close();
}

And below you would have something like:

private static boolean esNumeroPrimo(int numero)
{
    // Aqui comprobarias si es primo o no
        return true;
    else
        return false;
}

Here is how to check if a number is prime

link

    
answered by 30.08.2018 в 09:15