Java: Filereader reading number not in the file

Asked

Viewed 309 times

0

I have this TXT:

1,2,4,8,7
45,18,27,35,44
17,45,2,8,6

And I want to read this matrix to a Java array. Here’s the code:

    public static void main(String[] args){


        double[][] pesos = null;
        String valorFinal = "";
        String caracterAAdicionar = null;
        Double valorAAdicionar = null;

        try{
            FileReader arq = new FileReader("Entrada.txt"); 
            BufferedReader lerArq = new BufferedReader(arq);

            pesos = new double[3][5];
            /* Lendo matriz */
            for(int i=0; i < 3; i++){
                for(int j = 0; j < 5; j++){


                    if(j==4)                                                     //se estou no último valor da linha...
                           pesos[i][j] =Double.parseDouble(lerArq.read());              //...apenas leio esse valor
                    else{
                        System.out.println(lerArq.read());
                        caracterAAdicionar = String.valueOf(lerArq.read());
                        while (!caracterAAdicionar.equals(",")){
                            valorFinal = valorFinal + caracterAAdicionar;
                            lerArq.read();
                        }
                    }
                pesos[i][j] = Double.parseDouble(valorFinal);   
                }
            }
                    arq.close();
            }
            catch(FileNotFoundException f){
                f.printStackTrace();
            }
            catch(InputMismatchException f){
                /*System.out.print("Erro ocorreu em: " + i + " " + j);*/
                f.printStackTrace();
            }
            catch(IOException f){
                /*System.out.print("Erro ocorreu em: " + i + " " + j);*/
                f.printStackTrace();
            }
}

Problem: no While ( while (!caracterAAdicionar.equals(",")){ ), the program goes into infinite loop. Then, to debug, I print in lerArq.read() before entering this loop for the first time (as it is already in the code). And the result?

49

Yes, 49.And in the loop, the program keeps printing "49" forever.

But where the hell did he get that number from?

1 answer

1


There are two things you need to keep in mind regarding the method readof the Bufferedreader class:

  • It reads only one character in the file;
  • The return of the method is an integer.

Each character has its respective decimal representation, you can read more about it in: ASC II - Wikipedia

As the first character of your file is '1' (note that it is a character in your file and not a number) and the number '1' is represented by the number 49 in the decimal system (as you can see in the ASC II table of the link above)then as the method returns an integer this is why the number 49 is appearing.

With respect to the infinite loop, it occurs because you are comparing whether the variable caracterAAdicionar is different from "," (comma). Since your first character is '1', the condition will be true and enter the loop, the problem is that inside the loop you at no time change the value of the variable caracterAAdicionar or establishes a stop condition.

To avoid problems, it would be better if you used the method readline() from Bufferedreader to read line by line from your file and then get an array of line elements that will be delimited by ',' (comma) with the method splitof the String class, in which case your code would look like this:

public class Main {
    public static void main(String[] args){


        double[][] pesos = null;
        String valorFinal = "";
        String caracterAAdicionar = null;
        Double valorAAdicionar = null;

        try{
            FileReader arq = new FileReader("Entrada.txt"); 
            BufferedReader lerArq = new BufferedReader(arq);
            ArrayList <String> numEmString = new ArrayList<String>();

            String linhaArq;

            // Lendo cada linha do arquivo
            while ((linhaArq = lerArq.readLine()) != null) {

                // Pegando cada elemento separado por vírgula no arquivo
                for ( String caracteres : linhaArq.split(",") ){

                    // Adicionando os elementos em um ArrayList
                    numEmString.add(caracteres);                    
                }
            }

            pesos = new double[3][5];
            int k = 0;

            for ( int i = 0; i < 3; i++ ){
                for ( int j = 0; j < 5; j++ ){

                    // Convertendo cada string em Double e armazenando em 'pesos'
                    pesos[i][j] = Double.parseDouble(numEmString.get(k));
                    k++;

                }
            }


            arq.close();
        }
        catch(FileNotFoundException f){
            f.printStackTrace();
        }
        catch(InputMismatchException f){
            /*System.out.print("Erro ocorreu em: " + i + " " + j);*/
            f.printStackTrace();
        }
        catch(IOException f){
            /*System.out.print("Erro ocorreu em: " + i + " " + j);*/
            f.printStackTrace();
        }
    }
}
  • Great! Only one question remained: If read() always reads the characters in ASC||, what is the use of it?

  • The method read reads character by character in the file, the return of the method is an integer, but if you want to get the referent character in ASC II, you can use a cast, for example: char c = (char) lerArq.read(). On the other hand the method readLine() reads line by line in the file, but often you want to work with each character of the file and not with the entire line, in such cases the method read() is very useful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.