Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Java program for 2-D Array Maze

  1. #1
    Junior Member
    Join Date
    Mar 2009
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Java program for 2-D Array Maze

    Hello all,

    This is the last assignment of the year for me. A big one, and due by 11am on May 8th. It's a 2-D array problem.

    Assignment 8: CS 160 Foundations in Computing

    I'm not quite sure how to start this one. Once it's started and I get the basic outline, I feel like it'll be much easier since I'll just have to repeat those steps for the other locations. I'm not sure how to setup an array for one of the boxes so if someone could post up an example of some sort that'd be great so I can get started on this.

    Thanks,
    Peter


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Last Problem - 2-D Array Maze problem

    Hello Peetah05,

    You need to start this very much like the other assignment we helped you with. You will need a Scanner class which reads the users input from the console. You can also use the Scanner class to read the rooms.txt file.

    http://www.javaprogrammingforums.com...ner-class.html

    http://www.javaprogrammingforums.com...ner-class.html
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  3. #3
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Last Problem - 2-D Array Maze problem

    This will get you started...

    import java.util.Scanner;
     
    public class Dungeon {
     
        public static String option;
     
        public static void main(String[] args) {
     
            System.out.println("Welcome to my dungeon!");
            System.out.println("We have creepy crawly monsters roaming about. ");
            System.out.println("Find the escape route and win!");
            System.out.println("Or drop to your death in the deep pit.");
            System.out.println("Good luck!");
            System.out.println("");
     
            Scanner sc = new Scanner(System.in);
     
            System.out.println("Menu options: 'h' for help, 'n' for north, 's' for south, 'w' for west, 'e' for east, 'l' to look around, and 'q' for quit.");
     
            // Main loop looking for user input
            while (sc.hasNext()) {
     
                option = sc.next();
     
                // Option actions here
                if (option.equals("q")) {
                    System.out.println("Good bye!");
                    System.exit(1);
                } else if (option.equals("h")) {
                    System.out.println("Help: to play this game, you can move north, west, south or east.");
                    System.out.println("Type 'l' to take a look around at the room, or type 'q' to quit the game.");
                }
     
     
            }
     
            // Close scanner
            sc.close();
        }
    }

    I suggest you read up on 2D arrays.

    Java: Two-dimensional arrays as arrays of arrays
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  4. #4
    Junior Member
    Join Date
    Mar 2009
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Last Problem - 2-D Array Maze problem

    I have been quite busy with big papers and finals but here is what I have gotten done so far. I apologize for the poor coding and help, my teacher sucks at teaching...cant wait to be done with this class.

    I'm not quite sure how this is supposed to look. I tried, got some errors, just wanted to see what you could do it. I think this one might end up like the last one...not knowing how to do any of the assignment. Any help would be appreciated, again I apologize for the poor performance.

    import java.util.Scanner;
    import java.io.File;
    import java.io.FileNotFoundException;
     
    public class Dungeon {
     
        public String[] room = new String[];
     
    	public static String option;
        public static String roomFile;
     
        public void roomToArray () {
        	File file = new File(roomFile);
     
        	try {
        		Scanner scanner = new Scanner(file);
     
        		//Add each room to array
        		while (scanner.hasNextLine()) {
        			String line = scanner.nextLine();
        			roomFile[index] = line;
        			index ++;
        		}
        		scanner.close();
     
        	} catch (FileNotFoundException e) {
                e.printStackTrace();
                System.exit(1);
        	}
        }
     
        public static void main(String[] args) {
     
            System.out.println("Welcome to my dungeon!");
            System.out.println("We have creepy crawly monsters roaming about. ");
            System.out.println("Find the escape route and win!");
            System.out.println("Or drop to your death in the deep pit.");
            System.out.println("Good luck!");
            System.out.println("");
     
            Scanner sc = new Scanner(System.in);
     
            System.out.println("Menu options: 'h' for help, 'n' for north, 's' for south, 'w' for west, 'e' for east, 'l' to look around, and 'q' for quit.");
     
            // Main loop looking for user input
            while (sc.hasNext()) {
     
                option = sc.next();
     
                // Option actions here
                if (option.equals("q")) {
                    System.out.println("Good bye!");
                    System.exit(1);
                } else if (option.equals("h")) {
                    System.out.println("Help: to play this game, you can move north, west, south or east.");
                    System.out.println("Type 'l' to take a look around at the room, or type 'q' to quit the game.");
                }
     
     
            }
     
            // Close scanner
            sc.close();
        }
    }

  5. #5
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    820
    My Mood
    Cynical
    Thanks
    7
    Thanked 104 Times in 90 Posts

    Default Re: Last Problem - 2-D Array Maze problem

    My advice to you is follow the guidlines, it says you must implement some set functions so do that! Code them one by one and test each one at a time. Then worry about intergrating them all.

    I just coded this project in about 1.5 hours, whilst being distracted also. It has 1 very minor problem which i'll iron out later when I get chance.

    But take it bit by bit then you should be fine

    Also incase you are wonderng its taken me about 110 lines of code

    Chris

  6. #6
    Junior Member
    Join Date
    Mar 2009
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Last Problem - 2-D Array Maze problem

    Quote Originally Posted by Freaky Chris View Post
    My advice to you is follow the guidlines, it says you must implement some set functions so do that! Code them one by one and test each one at a time. Then worry about intergrating them all.

    I just coded this project in about 1.5 hours, whilst being distracted also. It has 1 very minor problem which i'll iron out later when I get chance.

    But take it bit by bit then you should be fine

    Also incase you are wonderng its taken me about 110 lines of code

    Chris
    Oh wow, you did that quite quick. I've been trying to follow those guidelines and use the methods suggested but can't get anything to work. If you'd post that up I'd be great, I'll also send you a pm for some extra things. I'd love to see what you've come up with so I can interpret the code and see how you got everything.

    Peter

  7. #7
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    820
    My Mood
    Cynical
    Thanks
    7
    Thanked 104 Times in 90 Posts

    Default Re: Last Problem - 2-D Array Maze problem

    Not really a big fan on doing this but I'm in a good mood so.
    Btw, My small problem was solved my learning Regex xD

    import java.io.FileReader;
    import java.util.Scanner;
    import java.util.regex.Pattern;
     
    public class Dungeon {
    	private String[][] dungeon = new String[6][4];
    	public void printWelcomeMessage(){
    		System.out.println("Welcome to my dungeon!");
    		System.out.println("We have creepy crawly monsters roaming about.");
    		System.out.println("Find the escape route and win!");
    		System.out.println("Or drop to your death in the deep pit.");
    		System.out.println("Good luck!");
    		System.out.println();
    		System.out.println("Menu options: 'h' for help, 'n' for north, 's' for south, 'w' for west, 'e' for east, 'l' to look around, and 'q' for quit.");
    	}
    	public void printHelp(){
    		System.out.println("Help: to play this game, you can move north, west, south or east.");
    		System.out.println("Type 'l' to take a look around at the room, or type 'q' to quit the game.");
    	}
    	public boolean readRoomFile(String file){
    		Scanner fs;
    		try{
    			fs = new Scanner(new FileReader(file));
    		}catch(Exception e){ return false; };
    		for(String temp;fs.hasNextLine();){
    			temp = fs.nextLine();
    			dungeon[Integer.parseInt(temp.split(";")[0])][Integer.parseInt(temp.split(";")[1])] = temp.split(";")[2];
    		}
    		return true;
    	}
    	public void printRoom(int row, int col){
    		System.out.println(dungeon[row][col]);
    	}
    	public String getRoomDescription(int row, int col){
    		return dungeon[row][col];
    	}
    	public boolean checkIfPit(int row, int col){
    		return Pattern.compile("[^a-zA-Z]pit[^a-zA-Z]").matcher(dungeon[row][col].toLowerCase()).find();
    	}
    	public boolean checkIsExitValid(int row, int col, char d){
    		String direction = "";
    		switch(d){
    			case 's': direction = "south"; break;
    			case 'w': direction = "west"; break;
    			case 'n': direction = "north"; break;
    			case 'e': direction = "east"; break;
    			default: break;
    		}
    		if(direction != "")
    			return Pattern.compile("[^a-zA-Z]"+direction+"[^a-zA-Z]").matcher(dungeon[row][col].toLowerCase()).find();
    		return false;
    	}
    	public Dungeon(String filename){
    		Scanner sin = new Scanner(System.in);
    		String choice;
    		Pattern goalp = Pattern.compile("[^a-zA-Z]goal[^a-zA-Z]");
    		boolean goal = true;
    		int roomx = 0, roomy = 0;
    		do{
    			if(goal){
    				while(!readRoomFile(filename)){
    					System.out.print("Please enter a valid file name: ");
    					filename = sin.next();
    				}
    				goal = false;
    				filename = "";
    				printWelcomeMessage();
    			}
    			System.out.print(">");
    			choice = sin.next();
    			if(choice.equals("h")) printHelp();
    			else if(choice.equals("l")) printRoom(roomy, roomx);
    			else if(choice.equals("n")||choice.equals("s")||choice.equals("e")||choice.equals("w")){
    				if(checkIsExitValid(roomy, roomx, choice.toLowerCase().charAt(0))){
    					switch(choice.charAt(0)){
    						case 'n': roomy -= 1; break;
    						case 's': roomy += 1; break;
    						case 'e': roomx += 1; break;
    						case 'w': roomx -= 1; break;
    						default: break;
    					}
    					printRoom(roomy, roomx);
    				}else{
    					System.out.print("There is no exit to the ");
    					switch(choice.charAt(0)){
    						case 'n': System.out.println("north."); break;
    						case 's': System.out.println("south."); break;
    						case 'e': System.out.println("east."); break;
    						case 'w': System.out.println("west."); break;
    					}
    				}
    			}
    			if(goalp.matcher(getRoomDescription(roomy, roomx).toLowerCase()).find() || checkIfPit(roomy, roomx) || choice.equals("q")){
    				goal = true;
    				System.out.println("Good Bye!");
    			}
    		}while(!choice.equals("q"));
    	}
    	public static void main(String[] args) {
    		if(args.length > 0) new Dungeon(args[0]);
    		else new Dungeon("");
    	}
    }
    Regards,
    Chris

  8. #8
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Last Problem - 2-D Array Maze problem

    Good work Chris, Peter ows you!

    Not much chance of passing the course otherwise
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  9. #9
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    820
    My Mood
    Cynical
    Thanks
    7
    Thanked 104 Times in 90 Posts

    Default Re: Last Problem - 2-D Array Maze problem

    Quote Originally Posted by JavaPF View Post
    Good work Chris, Peter ows you!

    Not much chance of passing the course otherwise
    Hehe, I didn't do it to help him I did it so I cna practise, since frankly I think my Java skills are poor. Care to comment on the code?

    Chris

  10. #10
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Last Problem - 2-D Array Maze problem

    Thats the main reason why I set up these forums, these types of questions are perfect for practasing Java and keeping your skills up to date.

    Your code looks very good. Nicely split into methods and its very similar to how I would of done it. There is no way I would say your Java skills were poor.

    I toned down the code I posted above to keep it all in the main method because Peter didn't sound like he had grasped the concept of OOP on his last assignment.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  11. #11
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    820
    My Mood
    Cynical
    Thanks
    7
    Thanked 104 Times in 90 Posts

    Default Re: Last Problem - 2-D Array Maze problem

    I Just followed the requirements for functions etc lol! I made a small change to the load file function
    	public boolean readRoomFile(String file){
    		Scanner fs;
    		try{
    			fs = new Scanner(new FileReader(file));
    		}catch(Exception e){ return false; };
    		for(String[] temp;fs.hasNextLine();){
    			temp = fs.nextLine().split(";");
    			dungeon[Integer.parseInt(temp[0])][Integer.parseInt(temp[1])] = temp[2];
    		}
    		return true;
    	}
    Last edited by Freaky Chris; May 8th, 2009 at 05:09 AM.

  12. #12
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Last Problem - 2-D Array Maze problem

    Yeah the requirements help out a lot. It's basically step by step. No excuse for not completing this
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

Similar Threads

  1. Logic to implement a program to display decimal place of a number
    By chronoz13 in forum Algorithms & Recursion
    Replies: 2
    Last Post: June 11th, 2009, 04:53 AM
  2. GUI problem with image in java
    By Kok in forum AWT / Java Swing
    Replies: 6
    Last Post: May 17th, 2009, 05:17 AM
  3. [SOLVED] Array loop problem which returns the difference between the value with fixed value
    By uplink600 in forum Loops & Control Statements
    Replies: 5
    Last Post: May 15th, 2009, 05:31 AM
  4. Error of missing return statement while implementing Array
    By MS_Dark in forum Collections and Generics
    Replies: 1
    Last Post: December 10th, 2008, 03:18 PM
  5. Replies: 1
    Last Post: November 22nd, 2008, 01:32 PM