I’m scanning a text file that has a sudoku board with a few separators. this is what a sample input would look like.
1 - - | 4 5 6 | - - -
5 7 - | 1 3 b | 6 2 4
4 9 6 | 8 7 2 | 1 5 3
======+=======+======
9 - - | - - - | 4 6 -
6 4 1 | 2 9 7 | 8 3 -
3 8 7 | 5 6 4 | 2 9 -
======+=======+======
7 - - | - - - | 5 4 8
8 r 4 | 9 1 5 | 3 7 2
2 3 5 | 7 4 $ | 9 1 6
where it has “|” as borders and =====+====+==== as dividers. I made this code to ignore the | and ====+===+=== but it’s skipping that part of the code and declaring them as invalid characters and adding 0’s in there place
public static int [][] createBoard(Scanner input){
int[][] nSudokuBoard = new int[9][9];
for (rows = 0; rows < 9; rows++){
for (columns = 0; columns < 9; columns++){
if(input.hasNext()){
if(input.hasNextInt()){
int number = input.nextInt();
nSudokuBoard[rows][columns] = number;
}//end if int
else if(input.hasNext("-")){
input.next();
nSudokuBoard[rows][columns] = 0;
System.out.print("Hyphen Found \n");
}//end if hyphen
else if(input.hasNext("|")){
System.out.print("border found \n");
input.next();
}// end if border
else if(input.hasNext("======+=======+======")){
System.out.print("equal row found \n");
input.next();
}// end if equal row
else {
System.out.print("Invalid character detected at... \n Row: " + rows +" Column: " + columns +"\n");
System.out.print("Invalid character(s) replaced with a '0'. \n" );
input.next();
}//end else
}//end reading file
}//end column for loop
}//end row for looop
return nSudokuBoard;
}//end of createBoard
I talked it over with a tutor but i don’t remember his suggestion on how to fix this.
Your loops increment the row and column counters even when you are consuming a border or a divider. So even after you fix other issues (as explained in the previous answer), you will finish filling the matrix before you’ve read all your input. You need to modify your code to conditionally advance the row and column counters only after you’ve consumed an integer or a dash. This would mean removing the
forloops, changing the firstif(input.hasNext())to awhile, and addingrows++andcolumns++in the places where you’ve consumed an integer or dash and are setting a value fornSudokuBoard[rows][columns]. You would also need logic to determine when to incrementrowsand when to setcolumnsback to0.Also, stylistically speaking, you should rename
rowstorowandcolumnstocolumn.