*
The moose likes Java in General and the fly likes Trying to fill a 2D array from a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Trying to fill a 2D array from a file" Watch "Trying to fill a 2D array from a file" New topic
Author

Trying to fill a 2D array from a file

Shaggy Rogers
Greenhorn

Joined: Mar 10, 2006
Posts: 26
I'm trying to fill a two-dimensional array (char Maze[][]) by reading data from a file, and have something like this.

//Fill the Array with maze values
for(int i = 0; i < maze.length; i++)
{
for(int x = 0; x < maze[0].length; x++)
{
maze[i][x] = Scanner.next();
}
}
However, maze is of type char, and .next() can only be used on strings of course. I also get the classic "static context error" with this code. Not sure how to get around this. THanks.
Shaggy Rogers
Greenhorn

Joined: Mar 10, 2006
Posts: 26
Worked out the static context error, but not sure how to go about match up the char array with a string data type still. I've tried things like creating a dummy string array and setting it equal to the char array, but to no avail.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
It's a bit odd, but Scanner doesn't have a nextChar() method. Perhaps it should. Maybeyou could use next("."), where "." is a regular expression for one character, any character. You could also call scanner.useDelimiter("") - after that, next() will always return a String containing single character. Or maybe it would work better (and probably be more straightforward) for you to use nextLine() to read an entire line as a single String, and then loop through the individual chars in the String using charAt(). I don't know what the format of the file is like, but those seem like good things to try out, at least.


"I'm not back." - Bill Harding, Twister
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Trying to fill a 2D array from a file
 
Similar Threads
Reading characters from a file into an array
Comparing chars at positions in an array
Filling an Array.
Bidimensional array to GUI?
July Newsletter Puzzle (Maze Solver)