Advertisement
LEANDRONIEVA

leerprimos

Sep 13th, 2023
1,054
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class LeerNumerosPrimos {
  4.  
  5.     public static Scanner scanner = new Scanner(System.in);
  6.  
  7.     public static void main(String[] args) {
  8.         // TODO Auto-generated method stub
  9.  
  10.         String contenido;  
  11.         String aux = "";
  12.         int numero;
  13.         LeerArchivos documento = new LeerArchivos();
  14.         System.out.println("Ingrese la dirección del archivo: ");
  15.         String direccion = scanner.nextLine();
  16.         System.out.println("Contenido del archivo: ");
  17.         contenido = documento.leerArchivoDeTexto(direccion);
  18.         System.out.println("Números primos dentro del archivo: ");
  19.        
  20.         for (char c: contenido.toCharArray()) {
  21.             if(c != ' ') {
  22.                 aux+=c;
  23.             }else {
  24.                 numero = Integer.parseInt(aux);
  25.                 if (esPrimo(numero)) {
  26.                     System.out.print(numero+" ");
  27.                 }
  28.                 aux="";
  29.             }
  30.         }
  31.     }
  32.    
  33.     private static boolean esPrimo(int num) {
  34.         int contador = 0;
  35.         int i = 2;
  36.         while(i<=(Math.sqrt(num))) {
  37.             if (num%i==0)contador++;
  38.             i++;
  39.         }
  40.         if (contador>0) return false;
  41.         return true;
  42.     }
  43.  
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement