File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Reading characters from a file into an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reading characters from a file into an array" Watch "Reading characters from a file into an array" New topic
Author

Reading characters from a file into an array

Shaggy Rogers
Greenhorn

Joined: Mar 10, 2006
Posts: 26
I have an array, maze[][] that is to be filled with characters from a text file. I've got most of the program worked out (i think) but can't test it because I am reading my file incorrectly. However, I'm running into major headaches with this part of the program.
The text file looks like this: (It is meant to be a maze, 19 is the size of the maze(assumed to be square). is free space, # is block, s is start, x is finish)
This didn't paste evenly, but thats not a big deal. Just giving an idea.
19
5..................
#...........#......
#.#....#####.......
#.....#............
##.......#...#.....
########.##........
##........#...#....
#######.#..........
#######.....#######
##########.....####
#.#....#####.######
#######......######
##########......###
###########.#######
##........#...#....
#######.#...#######
..........##.......
######...#.........



And my constructor looks like follows, I've tried zillions of things with the input.hasNext() and hasNextLine() to no avail.

Code:

//Scanner to read file

Scanner input = null;
try{
input = new Scanner(fileName);
}catch(RuntimeException e) {
System.err.println("Couldn't find the file");
System.exit(0);
}
//Set the size of the maze
while(input.hasNextInt())
{
size = input.nextInt();
}

//Set Limits on coordinates
Coordinates.setLimits(size);

//Set the maze[][] array equal to this size
maze = new char[size][size];

//Fill the Array with maze values

for(int i = 0; i < maze.length; i++)
{
for(int x = 0; x < maze[i].length; x++)
{
if(input.hasNextLine())
{
String insert = input.nextLine();

maze[i][x] = insert.charAt(x);
}

}
}
}


Any advice would be loved =D
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
I think that given your input file, the best thing to do would be read each line into an array. It looks like the first line in the text file tells how many rows there are in the maze. The String class has methods that should make the rest easy.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reading characters from a file into an array