Read txt file and add it to two arrays in java

0

They ask me for a method where I have to load a txt file and add it to two arrays, one text and one double. I have the following code and I want to know how to add it to the methods, I already have an idea but I do not know if it's okay.

Note the two cellular arrangements and rimes have already been declared.

** The code I have not tried because I need 5 more methods

public RegistroLlamadas() {

    String linea;
    String[] partes;

    try {

        fr = new FileReader("Archivos\Registro.txt");
        br = new BufferedReader(fr);

        while ((linea = br.readLine()) != null) {
            partes = linea.split("@");

        }

        ncelular[0] = linea;
        rminutos[0] = Double.parseDouble(linea);

        fr.close();

    } catch (Exception e) {

    }

}
    
asked by Mauricio 03.11.2017 в 22:19
source

1 answer

2

I assume from the code that the text file is composed of several lines, and that an "@" separates the number and the minutes.

In that case, within the same "while" loop you should store the results in arrays or arrays.

I'm not sure what the problem is, but if you do not know in advance how many rows your file has, you will not be able to create an array with the right size. I would use a collection, since its size is dynamic.

For example:

public RegistroLlamadas() {

    String linea;
    String[] partes;

    try {

        fr = new FileReader("Archivos\Registro.txt");
        br = new BufferedReader(fr);

        int posicion = 0;
        while ((linea = br.readLine()) != null) {
            partes = linea.split("@");

            ncelular[posicion] = linea;
            rminutos[posicion] = Double.parseDouble(linea);

            posicion++;

        }


        fr.close();

    } catch (Exception e) {

    }

}

One possible problem that you might encounter is that you can not know in advance how many lines the file has, and therefore, you will not be able to create an array that is the right size. A possible solution to this is that instead of a "primitive" array you use a dynamic collection, such as ArrayList.

    
answered by 04.11.2017 / 00:57
source