I’m writing a word search program that scans in from a text file. The text file contains two integers (the dimensions of the puzzle, which in this case is 10×10), followed by the puzzle, followed by another integer (the amount of words to find), and finally the words to be found. I am trying to write the code so that the program will execute a for loop which will scan the next line in, then add each character in the string to the 2D array. However, the scanner continues seems to continue through the file and eventually “out of bounds” on the file, even though, according to the for loop, it should run no more than 10 times (the dimension of the puzzle is 10×10)
Here is the problematic code:
Scanner scan = new Scanner(new File("puzzle.txt"));
int rows = scan.nextInt();
int columns = scan.nextInt();
int [][] wordSearch = new int[rows][columns];
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
String temp = scan.nextLine();
for (int k = 0; k < temp.length(); k++){
wordSearch[i][j] = temp.charAt(k);
}
}
}
Here is the puzzle.txt:
- 10 10
- WVERTICALL
- ROOAFFLSAB
- ACRILIATOA
- NDODKONWDC
- DRKESOODDK
- OEEPZEGLIW
- MSIIHOAERA
- ALRKRRIRER
- KODIDEDRCD
- HELWSLEUTH
- 10
- WEEK
- FIND
- RANDOM
- SLEUTH
- BACKWARD
- VERTICAL
- DIAGONAL
- WIKIPEDIA
- HORIZONTAL
- WORDSEARCH
No, look at your loop:
You’re running it for each row and each column. I suspect you actually want:
Of course, this assumes that you’ve correctly set the length of each line to the number of columns – you may want to validate that after you read the line.
One thing which should have raise suspicions was this inner loop:
That would overwrite the same
wordSearch[i][j]for every character intemp, making all but the last iteration pointless.