开发者

Trying to read from a file. Throws an exception

开发者 https://www.devze.com 2023-01-28 05:39 出处:网络
Im trying to read from a file containing a single vertical file of numbers, and filling a matrix (that is composed by JTextFields) with them, but when I try the set method, the program throws an excep

Im trying to read from a file containing a single vertical file of numbers, and filling a matrix (that is composed by JTextFields) 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());
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消