我正在写一个带有3位数字(x,y,z)的txt文件,其中x是行,y是列,z是我的数独网格的值。
我已经设法写了我的txt文件,其中每3行我有一个数字。第1行= x,第2行= y,第3行= z,然后第4行= x,第5行= y等等......
我在编写部分代码时无法读取txt文件,然后在控制台的右侧坐标处打印我的值。
我确信我的代码中有很多错误。这是我在控制台上打印的方法:
static void imprimerGrille()
{
try
{
BufferedReader lectureTexte = new BufferedReader(new FileReader("partie.txt"));
String ligne = lectureTexte.readLine();
int count = 0;
while ((ligne = lectureTexte.readLine()) != null){
for (int i=0; i<grilleSudoku.length; i++){
System.out.print("\n");
if (i%3 == 0)
System.out.println();
for (int j=0; j<grilleSudoku.length; j++){
if (j%3 == 0)
System.out.print(" ");
if (count%3 == 0){
//This would be the value I want in line, column coordinate
}
else if (count%3 == 1){
//This is my line coordinate
}
else if (count%3 == 2){ //colonne
//This is my column coordinate
}
}
}
count++;
if (count == 3){
count = 0;
}
}
} catch(Exception ex){
System.out.println("Fichier inexistant");
}
}
我这里有这个代码用0打印我的数独网格的布局。我在将它与BufferedReader部分合并时遇到了麻烦。
/*for (int i=0; i<grilleSudoku.length; i++){
System.out.print("\n");
if (i%3 == 0) System.out.println();
for (int j=0; j<grilleSudoku.length; j++){
if (j%3 == 0) System.out.print(" ");
for (int x = 0; x<9; x++){
if (grilleSudoku[i][j] == x) System.out.print(x);
}
}
} */
使用给定的txt结构,您可以执行类似的操作
int[][] sudoku = new int[3][3];
try (BufferedReader br = new BufferedReader(new FileReader("<your-input-file>"))) {
String line;
int i = 1;
int row = 0;
int column = 0;
while ((line = br.readLine()) != null) {
if (i++ % 3 == 0) {
sudoku[row][column++] = Integer.parseInt(line);
if (column % 3 == 0) {
++row;
column = 0;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(String.format("%d ", sudoku[i][j]));
}
System.out.println();
}
我建议将你的txt更改为这种格式(不是有效的数独):
1,2,3
4,5,6
7,8,9
它有利于编写更清晰的代码,可读的输入,如果您想将网格更改为4x4,您只需要更改输入文件和二维数组。 (如果使用ArrayList,则只需要修改文件)
int[][] sudoku = new int[3][3];
try (BufferedReader br = new BufferedReader(new FileReader("<your-input-file>"))) {
String line;
int row = 0;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(",");
for (int column = 0; column < splitted.length; column++) {
sudoku[row][column] = Integer.parseInt(splitted[column]);
}
row++;
}
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(String.format("%d ", sudoku[i][j]));
}
System.out.println();
}