Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Reading in spaces as well as characters with the Scanner

$
0
0
Hello I want to be able to read in mazes from a properly formatted text file with the size of the maze by row and colum at the top followed by the maze using asterisk(*) for walls and a space for pathway. The entry would look something like this:
9 20
********************
* * *
** ** ***** ** *****
* * * * * *
* * * * * * *
* * * *
************* ** *
*
********************
I can't seem to figure this out even when setting the delimiter to nothing(""). I can get it to work with sapces between each asterisks and dashes instead of spaces for paths, which looks like this:
9 20
* * * * * * * * * * * * * * * * * * * *
* - - - - - - * - - - - - - - - - - - *
* * - * * - * * * * * - * * - * * * * *
* - * - * - - - - - * - * - - - - - - *
* - - - * - - - - - * - - - * - * - * *
* - - - - - * - - - - - - - - - - * - *
* * * * * * * * * * * * * - - * * - - *
* - - - - - - - - - - - - - - - - - - G
* * * * * * * * * * * * * * * * * * * *
Note: The G represents the goal.
Here is the code that I've been trying to get to work for the first one:
	//My method to populate and create the maze.
	private static String[][] populateMaze() {
		JFileChooser fchoose = new JFileChooser();//This finds a text file via JFileChooser
		int returnVal = fchoose.showOpenDialog(null);
		if(returnVal == JFileChooser.APPROVE_OPTION)
			//Try catch in order to open the file, scan it, 
			//and then populate my String array with it
			try {
				//Creating a scanner attached to the selected file.
				Scanner in = new Scanner(fchoose.getSelectedFile());
				//Using the first two ints in the .txt to create my Array
				String[][] maze = new String[in.nextInt()][in.nextInt()];
				in.useDelimiter("");//Setting my delemiter to nothing.
				for(int row = 0; row < maze.length; row++){//Nested for's to populate the maze
					for(int col = 0; col < maze[0].length; col++){
						maze[row][col] = in.next();//Getting the next thing in the file
					}
				}
				return maze;//Returns the completed maze
			//Catching errors	
			} catch (FileNotFoundException e1) {
			} catch (IOException e1) {
			}
		//fallback to deal with the compiler
		String[][] fallBack = new String[9][20];
		return fallBack;
		}

Anyone have any ideas or advice to give me to get this thing to work? I've been pulling my hair out to figure it out.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>