Ejercicio de Java - Números primos

Iniciado por SiriusBl@ck, Noviembre 04, 2018, 06:13:15 PM

Tema anterior - Siguiente tema

0 Miembros y 2 Visitantes están viendo este tema.

Noviembre 04, 2018, 06:13:15 PM Ultima modificación: Noviembre 04, 2018, 07:22:47 PM por SiriusBl@ck
¡Buenas tardes Underc0de!

La consigna: Realizar un programa en Java que, calcule todos los números primos en cierto rango establecido.

Problemas a solucionar:

Deben estar separados por guion.
El programa debe tener la función ¿Desea continuar / SI o NO?
Si los números son ingresados al revés (es decir, que ingresen n1 > n2) también te calcule el rango.

PD: No sé casi nada de java, pero me está divirtiendo aprender.
En fin, dejo adjunto mi código incompleto con errores por si alguien gusta divertirse también.

Código: text
public static void main(String[] args) {

        int i, j;
        boolean esPrimo;
        boolean seguir = true;
        int Inicio = 2;
        int Final;
       
        Scanner sc = new Scanner(System.in);
       
       while (seguir) {
       
        System.out.println("Ingrese un nùmero inicial ");
        Inicio = sc.nextInt();
        System.out.println("Ingrese un número final ");
        Final = sc.nextInt();
       
        for (i = Inicio; i <= Final; i++) {
            esPrimo = true;
            for (j = 2; j < i; j++) {
            if (i % j == 0) {
                esPrimo = false;
            }
            }
         
            if (esPrimo) {
                System.out.print(i+"  -  ");
               
            } 
        }

            System.out.println("Estos son todos los números primos entre el rango establecido");
           
      }else
   
{
        boolean seguir = false;
       
                 System.out.print("¿Desea continuar? ");
                 System.out.println("S / N ");
        String opc = sc.next();
        if (opc.equals("s") || opc.equals("S")) {
           
        }
               }
}



¡Saludos!
Es intrigante. ¿Cómo es que esas personas, que son tratadas como ganado en esta aburrida sociedad, no han intentado destruirla?

Shōgo Makishima

Noviembre 11, 2018, 12:40:04 PM #1 Ultima modificación: Noviembre 20, 2018, 09:59:21 AM por SiriusBl@ck
Algunas cosas solucionadas:

Código: text
 /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package numerosprimos;

import java.util.Scanner;


/**
*
* @author Toshiba
*/
public class NumerosPrimos {
public static void main(String[] args) {

     int i, j;
        boolean esPrimo;
        boolean seguir = true;
        int Inicio = 2;
        int Final;
        String respuesta = " ";
           
        Scanner sc = new Scanner(System.in);
       
while(seguir) {

System.out.println("Ingrese un nùmero inicial ");
        Inicio = sc.nextInt();
        System.out.println("Ingrese un número final ");
        Final = sc.nextInt();   

for (i = Inicio; i <= Final; i++) {
            esPrimo = true;
            for (j = 2; j < i; j++) {
            if (i % j == 0) {
                esPrimo = false;
            }
           
            if (esPrimo) {
                System.out.print(i+"  -  ");

    }
  }
} // end  for!

System.out.println("Estos son todos los números primos en el rango establecido");

System.out.println("Desea continuar? S/N");
             respuesta = sc.next();
             if (respuesta.equalsIgnoreCase("s"))
                seguir = true;
             else
                seguir = false;   
                                   
            }
         }
      }
Es intrigante. ¿Cómo es que esas personas, que son tratadas como ganado en esta aburrida sociedad, no han intentado destruirla?

Shōgo Makishima

Soluciones:

Código: text

public class NumerosPrimos {
public static void main(String[] args) {

        int i, j;
        boolean esPrimo;
        boolean seguir = true;
        int Inicio = 2;
        int Final;
        String respuesta = "YES";
           
        Scanner sc = new Scanner(System.in);
       
        while(seguir) {
           
                System.out.println("Ingrese un nùmero inicial ");
                Inicio = sc.nextInt();
                System.out.println("Ingrese un número final ");
                Final = sc.nextInt();   

            for (i = Inicio; i <= Final; i++) {
                    esPrimo = true;
                    for (j = 2; j < i; j++) {
                    if (i % j == 0) {
                    esPrimo = false;
            }
           
          }         
                if (esPrimo) {
                System.out.print(i+"   ");

    }
    }
// end  for!

                    System.out.println("Estos son todos los números primos en el rango establecido");
           
                        System.out.println("Desea continuar? S/N");
                            respuesta = sc.next();
                            seguir = respuesta.equalsIgnoreCase("s");                       
        }
     }
}

Es intrigante. ¿Cómo es que esas personas, que son tratadas como ganado en esta aburrida sociedad, no han intentado destruirla?

Shōgo Makishima

Hola SiriusBl@You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login,

Me parece bien el codigo, te recomendaría tres cosas:


  • Puedes usar un break dentro del condicional justo despues de que se determina que no es un número primo. De esta forma, el bucle termina y no se queda hasta que halla llegado a la variable Final.
  • Todo ese bucle for puede extraerse y colocarse dentro de un método aparte, el codigo puede volverse mas claro y facil de entender. También, le ayudara a aprender llamadas de métodos.
  • Aprende a usar git. Esto te ayudará a tener el codigo ordenado respecto a las muchas versiones que pueden surgir. Todos los IDEs de Java (Eclipse, Netbeans o IntelliJ) soportan integraciones con Git y puedes publicar tu codigo en Github

Saludos...