Extract integers from a JAVA string

3

I have this string ( LIXA ABIMERHI JUAN JOSE,DISEÑO DE INTERFACES,90,88,81,90 ) and they are asking me:

  • Read the data by lines using the split method of the class String separate the fields.
  • Convert the 4 strings of grade text to the whole number and calculate the average of them.
  • (they are strings contained in a file)

    My code:

    Scanner sc = new Scanner(System.in);
    File file = new File("E:/SEMESTRE2/POO/PROGRAMAS/TareasSem2/src/U6/Calificaciones.txt");
    if (!file.exists()) 
    {
        System.out.println ("No existe el archivo: "+file);
        System.exit(1);
    }
    System.out.println ("Archivo Encontrado");
    System.out.print ("Escribe El Promedio Minimo ");
    int prom = sc.nextInt();
    try 
    {
    
        FileReader fr = new FileReader(file);
        BufferedReader bfr = new BufferedReader(fr);
        String linea=bfr.readLine();
        String[] parts = linea.split(","); 
    
        //nombre> parts[0] materia parts[1] num1 parts [2]
    
        //System.out.println(linea);
        while (linea != null) 
        {
                double num = 0, mat, promA = 0;
                for(int i = 2;i>=2&&i<=5;i++)
                {
    
                mat=Double.parseDouble(parts[i]);
                num = num + mat;
                promA = num / 4;
    
                }
                System.out.println(linea+"  "+promA);
    
    
            linea=bfr.readLine();
        }
        /*while (linea != null) 
        {
            double num = 0, mat, promA = 0;
                for(int i = 2;i>=2&&i<=5;i++)
                {
    
                mat=Double.parseDouble(parts[i]);
                num = num + mat;
                promA = num / 4;
    
                }
    
                System.out.println(promA);
            linea=bfr.readLine();
        }*/
        bfr.close();
        fr.close();
    }
    catch (java.io.FileNotFoundException ex) 
    {
        System.out.println ("No existe el archivo: "+file);
    }
    catch (java.io.IOException ex) 
    {
        System.out.println ("Error al leer el archivo: "+file);
    }//fin del catch IO
    

    ok I found just like that now it always prints the same average and does not restart

        
    asked by Johann Duran 24.11.2017 в 15:21
    source

    2 answers

    0

    to load the file I suggest this code:

    public List<String> cargarArchivo(String direccion){
        List<String> lineas = new ArrayList<>();
    
        try {
            Path ruta = Paths.get(direccion);
            Stream<String> flujoFormateado = Files.lines(ruta, Charset.forName("UTF-8")); // cargando el archivo plano
            flujoFormateado.forEach(lineas::add); // almacenando todos los elementos para su analisis
    
            System.out.println("lineas guardadas: "+lineas.size());
        } catch (IOException ex) {
            Logger.getLogger(Otros.class.getName()).log(Level.SEVERE, null, ex);
        }
    
        return lineas;
    }
    

    After having all the lines of interest you can go through them and take the average of each of them, but taking into account the example you gave you can do the following:

    public void calculoPromedio(){
        String cadena = "LIXA ABIMERHI JUAN JOSE,DISEÑO DE INTERFACES,90,88,81,90";
        String partes[] = cadena.split(",");
    
        System.out.println("s: "+cadena.split(",").length);
    
        double promedio = ( Integer.valueOf(partes[2]) + Integer.valueOf(partes[3]) + Integer.valueOf(partes[4]) + Integer.valueOf(partes[5]) )/4; 
        System.out.println("promedio: "+promedio);        
    
    }
    
        
    answered by 27.11.2017 в 23:00
    0

    Forgive me, English is my first language. Do not hesitate to ask for clarifications.

    We can make the string legends with the utility Scanner .

    String direccion = "cadenas.dat";
    File documento = new File(direccion);
    Scanner lector = null;
    try {
        lector = new Scanner(documento);
    } catch (FileNotFoundException e1) {
        System.err.println("No puedo leer " + direccion);
        System.exit(1);
    }
    System.out.println("Archivo encontrado.");
    
    Scanner teclado = new Scanner(System.in);
    System.out.print("Escribe el promedio minimo: ");
    double minPromedio = teclado.nextDouble();
    
    
    // Verificas que el documento tiene mas lineas por leer.
    while(lector.hasNextLine()) {
        String linea = lector.nextLine();
    
        String[] partes = linea.split(",");
        String nombre = partes[0];
        String profesion = partes[1];
    
        double calSuma = 0; // La suma de los calificaciones
        int cuantosCal = 0; // La numero de calificaciones que inclue en los calculaciones.
        for(int i = 2; i < partes.length; i++) {
            try {
                double calificacion = Double.parseDouble(partes[i]);
                cuantosCal++;
                calSuma += calificacion;
            } catch (Exception e) {
                System.err.print("Encontre un numero que no puedo leer.");
                continue; // Omites la numero corriente.
            }
        }
    
        double promedio = calSuma / cuantosCal;
    
        System.out.println(nombre + " tiene un calificacion promedio de " + promedio + ".");
    
        // Verificas que la promedio es el mismo o mas alto de la promedio minimo.
        if(promedio >= minPromedio) {
            System.out.println(nombre
                    + " tiene un calification promedio que cumple con el requisito.");
        }
    }
    
    lector.close();
    teclado.close();
    

    I think this code can make you want to, but this design is hard to change by code that you can restart.

    If you want code that you can restart, you need to put the lines in a List before doing the calculations, because the utility Scanner can not go back to the beginning of the file (except when reinitializing the Scanner object).

        
    answered by 20.12.2018 в 10:01