Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading characters from a file into an array

 
Shaggy Rogers
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic