Reputation: 35
I'm trying to load file, which looks like this:
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
to 2d array, which is in class sudokuboard.
The function, which i use for this is following:
@Override
public SudokuBoard read() throws DaoException {
SudokuBoard board = new SudokuBoard();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
while (in.ready() == true) {
for (int row = 0; row < 9; row++) {
for (int column = 0; column < 9; column++) {
board.setDigit(row, column, in.read());
//System.out.print(in.read() + ", ");
}
in.read(); // this is important
System.out.println("");
}
}
} catch (IOException e) {
throw new DaoException(DaoException.IO_EXCEPTION, e);
}
return board;
}
What i have after reading this file is:
0 0 0 6 115 113 0 126 0
0 0 0 4 115 113 0 126 0
0 0 0 2 115 113 0 126 0
0 0 0 3 115 113 0 126 0
0 0 0 8 115 113 0 126 0
0 0 0 5 115 113 0 126 0
0 0 0 1 115 113 0 126 0
0 0 0 9 120 120 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1
Anybody knows where the problem is ?
Thanks for help !
Upvotes: 1
Views: 5899
Reputation: 49
I've been playing with your code a bit. And this is what I came up with. Surely, there are better solutions, but I think this one will work for you.
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream("C:/Users/Rod/Desktop/123.txt")));
int column = 0;
int row = 0;
int pom;
while ((pom = in.read()) != -1) {
pom -= 48;
if (pom > -1 && pom < 10) {
System.out.print("" + pom + ", ");
// board.setDigit(row, column, pom);
column++;
if (column > 8) {
column = 0;
System.out.println("");
row++;
if (row > 8)
break;
}
}
}
} catch (Exception e) {
System.out.print("ERROR");
// e.printStackTrace();
} finally {
if (in != null)
in.close();
}
Tell me did it worked well for you.
P.S. I've edited code after comments. All the best.
Upvotes: 0
Reputation: 1927
What do you think about this solution?
public static int[][] readBoard(String boardFileName) throws IOException {
int[][] board = new int[9][9];
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(boardFileName));
for(int i = 0; i < 9 && reader.ready(); i++) {
String[] splittedRow = reader.readLine().split(" "); // split using the space character
for(int j = 0; j < 9; j++) {
board[i][j] = Integer.parseInt(splittedRow[j]);
}
}
return board;
} catch(IOException e) {
throw e; // lets the caller manage the exception
} finally {
assert reader != null;
reader.close();
}
}
Obviously, don't take care about the error management that is completely absent :)
I hope that this code will help you...
Upvotes: 1