RAUL-SUAREZ

tp0-punto4

Aug 29th, 2021
1,319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. package tp0Modulo;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class punto4 {
  6.  
  7.     public static void main(String[] args) {
  8.         // TODO Auto-generated method stub
  9.         Scanner sc = new Scanner(System.in);
  10.         punto4primos obj = new punto4primos();
  11.         int numero = validarNumero(sc, "ingrese un numero positivo");
  12.  
  13.         System.out.println("el numero " + numero + " es primo? " + obj.esPrimo(numero));
  14.  
  15.     }
  16.  
  17.     public static int validarNumero(Scanner valorIngresado, String mensaje) {
  18.         int numero;
  19.         String linea;
  20.         while (true) {
  21.             try {
  22.                 System.out.println(mensaje);
  23.                 linea = valorIngresado.nextLine();
  24.                 numero = Integer.parseInt(linea);
  25.                 break;
  26.             } catch (Exception e) {
  27.                 System.out.println("ERROR!!! INGRESE UN NUMERO POSITIVO");
  28.             }
  29.         }
  30.         return numero;
  31.     }
  32. }
  33. ########esta parte copiar en una nueva clase ########
  34. package tp0Modulo;
  35.  
  36. public class punto4primos {
  37.  
  38.     public boolean esPrimo(int x) {
  39.         boolean primo = true;
  40.         if (x == 1 || ((x % 2) == 0 && x > 2)) {
  41.             primo = false;
  42.  
  43.         } else {
  44.             for (int i = 2; i < (x / 2); i++) {
  45.                 if (x % i == 0) {
  46.                     primo = false;
  47.                     break;
  48.                 }
  49.             }
  50.         }
  51.         return primo;
  52.     }
  53.  
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment