I\'m creating (In Java) a boggle board solver using a board given to us in a .tx
ID: 3780126 • Letter: I
Question
I'm creating (In Java) a boggle board solver using a board given to us in a .txt file. I'm supposed to read it using either a BufferedReader or Scanner object and input the Strings into a 2d String array. This is what I have so far:
Scanner boardFile = new Scanner( new File(args[0]));
String size = boardFile.next();
int dimensions = Integer.parseInt(size);
String[][] board = new String[dimensions][dimensions];
String[] tempString = new String[dimensions];
while (boardFile.hasNextLine())
{
for (int r = 0 ; r < board.length - 1 ; r++)
{
for (int c = 0 ; c < board[r].length - 1 ; c++)
board[r][c] = boardFile.next();
}
}
The txt file is given to us as (this is the 4x4 board):
4
qu e a i
n e r e
t w s t
o r k y
The issue I'm having is in the line that says for(int c = 0 ; c < board[r].length-1 ; c++). The error message I'm receiving is:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Boggle.main(Boggle.java:20)
I'm not sure what I'm doing wrong when trying to read in this file?
Explanation / Answer
Here is the successfully compiling code for you:
import java.io.*;
import java.util.*;
class BoggleBoardSolver
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner boardFile = new Scanner( new File(args[0]));
String size = boardFile.nextLine();
int dimensions = Integer.parseInt(size);
String[][] board = new String[dimensions][dimensions];
String[] tempString = new String[dimensions];
while (boardFile.hasNextLine())
{
for (int r = 0 ; r < board.length ; r++)
{
for (int c = 0 ; c < board[r].length; c++)
board[r][c] = boardFile.next();
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.