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?
Great! Only one question remained: If read() always reads the characters in ASC||, what is the use of it?
– Mr Guliarte
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 methodreadLine()
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 methodread()
is very useful.– Alexandre Lara