Java: FileReader reading number that is not in the file

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 array to a Java array. Here is 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 give a print in lerArq.read( ) before entering this loop for the 1st time (as it is already in the code). And the result?

49

Yes, 49.E, in the loop, the program will print "49" forever.

But where the hell did he get that number from?

    
asked by anonymous 23.05.2015 / 04:03

1 answer

1

There are two things you need to keep in mind regarding the read method of the BufferedReader class:

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

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

p>

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 ASCII table of the link above), then as the method returns an integer this is the reason the number 49 is appearing.

Regarding the infinite loop, it occurs because you are comparing whether the variable caracterAAdicionar is different from the "," (comma). As your first character is '1', the condition will be true and you enter the loop, the problem is that within the loop you do not change the value of caracterAAdicionar or set a stop condition at any time.

To avoid problems, it would be best if you used the readline() BufferedReader method to read line by line of your file and then get an array of line elements that will be delimited by ',' (comma) with method split of 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();
        }
    }
}
    
23.05.2015 / 07:57