Trying to read from a file. Throws an exception
Im trying to read from a file containing a single vertical file of numbers, and filling a matrix (that is composed by JTextField
s) with them, but when I try the set method, the program throws an exception after changing to the second row
for(int a=0; a < i; a++) {
for(int b=0; b < i; b++){
// x = raf.readLine();
matrix[a][b].setText(raf.readLine());开发者_Go百科
}
}
You should not read a file from a GUI class. Try separating concerns by creating a dedicated class for reading the text file. Perhaps let your file reader class return an Iterator<String>
of lines. Now test your file reader class in a unit test and make sure it displays the lines correctly.
Then do something like this:
Iterator<String> lines = yourHelperClass.getLines()
for(int a=0; a < i; a++) {
for(int b=0; b < i; b++){
if(!lines.hasNext()){
// not enough lines, probably throw an Exception here
}
matrix[a][b].setText(lines.next());
}
}
That way it will be a lot easier to find out what is actually going wrong.
Recommended read: Coupling and Cohesion: The Two Cornerstones of OO Programming
You probably want something more like the example below, using some suitable values for WIDTH
and HEIGHT
.
for (int row = 0; row < HEIGHT; row++) {
for (int col = 0 ; col < WIDTH; col++) {
matrix[row][col].setText(raf.readLine());
}
}
精彩评论