How can I pass the data from the file to int? [closed]

0

In a CSV file, the results of a race are stored in the format name: seconds. The program will convert this data into an ArrayList. Then the user will be asked how many data he wants to see (n) and the n participants will be listed with the best time; for that the runner will be looked for with the shortest time and will be eliminated from the ArrayList, until completing the list.

public static void main(String[] args) throws FileNotFoundException {
    int numero = 0;

    File f = new File("datos.dat");
    Scanner fichero = new Scanner(f);

    ArrayList<String> datos = new ArrayList();
    String linea;
    int t1=0;
    while (fichero.hasNext()) {
        linea = fichero.nextLine();
        if (datos.size()==0){
           datos.add(linea);
        } else {
           t1=Integer.parseInt(linea.substring(linea.indexOf(";")));

        }
    }
    System.out.println(t1);
    Scanner teclado = new Scanner(System.in);

    numero = teclado.nextInt();
    numero = numero - 1;

    for (int i = 0; i <= numero; i++) {
        System.out.println(datos.get(i));
    }

}
    
asked by Héctor Huertas 10.01.2018 в 18:45
source

1 answer

0

To convert a string to an integer you must use Integer.parseInt(); but it would not work for you since you do not have the number separated from the name, if you try to convert to a non-number you will get an error: here I leave the solution to the problem you have:

// Create a class that will contain the parts of each line in the file

class Carrera {

   private String nombre;
   private int segundos;

   public Carrera(String nombre, int segundos) {
      this.nombre = nombre;
      this.segundos = segundos;
   }

   public String getNombre() {
      return nombre;
   }

   public int getSegundos() {
      return segundos;
   }

   @Override
   public String toString() {
      return "Carrera{" + "nombre=" + nombre + ", segundos=" + segundos + '}';
   }
}

// Modify your code like this:

public static void main(String[] args) throws FileNotFoundException {
        int numero = 0;

        File f = new File("datos.dat");
        Scanner fichero = new Scanner(f);

        ArrayList<Carrera> datos = new ArrayList();
        while (fichero.hasNext()) {

            String linea = fichero.nextLine();
            String columnas[] = linea.split(";");

            datos.add(new Carrera(columnas[0], Integer.parseInt(columnas[1])));
        }

        //Ordenamos de menos a mayor
        datos.sort(new Comparator<Carrera>() {
            @Override
            public int compare(Carrera o1, Carrera o2) {
                return o1.getSegundos() - o2.getSegundos();
            }
        });

        Scanner teclado = new Scanner(System.in);

        numero = teclado.nextInt();
        numero = numero - 1;

        for (int i = 0; i <= numero; i++) {
            System.out.println(datos.get(i));
        }
    }
    
answered by 10.01.2018 / 20:34
source