Page 1 of 3 123 LastLast
Results 1 to 20 of 44
Like Tree1Likes

Thread: How do I cycle through objects, then use a method from the found object?

  1. #1
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default How do I cycle through objects, then use a method from the found object?

    Java Code:
    import java.util.*;
    
    public class Practice{
    	
    	public static void main(String[] args) {
    		//setup dirNames
    		String[] dirName = {"north", "south", "east", "west"};
    		String[] shortDirName = {"n", "s", "e", "w"};
    		
    		//Setup vars
    		Vector exits = new Vector();
    		
    		//Make rooms
    		Room test = new Room("Sup", "This is test room");
    		test.setCurrInside(true);
    		Room otherRoom = new Room("Sup", "This is test room 2");
    		
    		//Make exits
    		test.addExit(new Exit("north", otherRoom));
    		otherRoom.addExit(new Exit("south", test));
    		
    		//Setup input and read it for dirs
    		Scanner sc = new Scanner(System.in);
    		String input = sc.nextLine();
    		input = input.toLowerCase();
    		
    		for(int i = 0; i < ; i++){
    			
    		}
    		
    		for(int x = 0; x < dirName.length; x++){
    			if(input.equals(dirName[x]) || input.equals(shortDirName[x])){
    				
    			}
    		}
    	}
    }
    Java Code:
    import java.util.*;
    
    public class Room {
    	
    	private String title;
    	private String desc;
    	private boolean currInside;
    	public static int roomAmount;
    	Vector vecExits = new Vector();
    	
    	public Room(String title, String desc){
    		this.title = title;
    		this.desc = desc;
    		roomAmount += 1;
    	}
    	
    	public String getTitle(){
    		return title;
    	}
    	
    	public String getDesc(){
    		return desc;
    	}
    	
    	public boolean getCurrInside(){
    		return currInside;
    	}
    	
    	public void setCurrInside(boolean currInside){
    		this.currInside = currInside;
    	}
    	
    	public void addExit(Exit exit){
    		vecExits.addElement(exit);
    	}
    	
    	public void removeExit(Exit exit){
    		if(vecExits.contains(exit)){
    			vecExits.removeElement(exit);
    		}
    	}
    	
    	public Vector getExits (){
    		return (Vector)vecExits.clone();
    	}
    }
    Java Code:
    public class Exit {
    	
    	private String dir;
    	private Room dest;
    	public static int exitAmount;
    	
    	public Exit(String dir, Room dest){
    		this.dir = dir;
    		this.dest = dest;
    		exitAmount += 1;
    	}
    	
    	public String getDir(){
    		return dir;
    	}
    	
    	public Room getDest(){
    		return dest;
    	}
    }
    So basically, I want to have the player change rooms if they input a correct direction, but I have no idea how to cycle through objects then use a method from them.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I cycle through objects, then use a method from the found object?

    Can you explain in a bit more detail. What are you trying to cycle through?

    Also, consider using an enum for your Directions.

  3. #3
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    I am simply trying to cycle through all the Room objects, and using the getCurrInside method to see which one the player is inside, then using that in my other for loop to get the exits destination and dir.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I cycle through objects, then use a method from the found object?

    I imagine that the Player himself will "know" which room he's in -- will have a property that indicates his location, and also the House or GameMap class will have a list of Players it holds as well as a graph of all the rooms.

    If you have a Player object, you can probably query it to get its current Room. I suppose you could give the Room class a boolean variable exitAvailable(Direction dir), or something similar. Again, I'd make Direction an enum and give it String fields for its short and long names.

  5. #5
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    I posted the entire code, I have no player class, I just said "player" referring to the person playing the game. By the way, it's a text adventure. I should probably make one, I can imagine having a setLocation and getLocation method in a player class could be very helpful xD

  6. #6
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    Java Code:
    import java.util.*;
    
    public class Practice{
    	
    	private static String name;
    	private static Room currLocation;
    	
    	public static void main(String[] args) {
    		//setup dirNames
    		String[] dirName = {"north", "south", "east", "west"};
    		String[] shortDirName = {"n", "s", "e", "w"};
    		
    		//Setup vars
    		Vector exits = new Vector();
    		Scanner sc = new Scanner(System.in);
    		
    		//Get name
    		System.out.print("What is your name? ");
    		name = sc.nextLine();
    		
    		//Make rooms
    		Room test = new Room("Sup", "This is test room");
    		Room otherRoom = new Room("Sup", "This is test room 2");
    		
    		//Create player object
    		Player player = new Player(name, test);
    		player.setLocation(test);
    		
    		//Make exits
    		test.addExit(new Exit("north", otherRoom));
    		otherRoom.addExit(new Exit("south", test));
    		
    		//Setup input and read it for dirs
    		String input = sc.nextLine();
    		input = input.toLowerCase();
    		currLocation = player.getLocation();
    		
    		for(Enumeration e = currLocation.getExits().elements(); e.hasMoreElements();){
    			Exit exit = (Exit)e.nextElement();
    		}
    		
    		for(int x = 0; x < dirName.length; x++){
    			if(input.equals(dirName[x]) || input.equals(shortDirName[x])){
    				currLocation = exit.getDest();
    				player.setLocation(currLocation);
    				showLocation();
    			}
    		}
    	}
    
    	private static void showLocation() {
    		System.out.println(currLocation.getTitle());
    		System.out.println(currLocation.getDesc());
    	}
    }
    Java Code:
    import java.util.*;
    
    public class Room {
    	
    	private String title;
    	private String desc;
    	public static int roomAmount;
    	Vector vecExits = new Vector();
    	
    	public Room(String title, String desc){
    		this.title = title;
    		this.desc = desc;
    		roomAmount += 1;
    	}
    	
    	public String getTitle(){
    		return title;
    	}
    	
    	public String getDesc(){
    		return desc;
    	}
    	
    	public void addExit(Exit exit){
    		vecExits.addElement(exit);
    	}
    	
    	public void removeExit(Exit exit){
    		if(vecExits.contains(exit)){
    			vecExits.removeElement(exit);
    		}
    	}
    	
    	public Vector getExits (){
    		return (Vector)vecExits.clone();
    	}
    }
    Java Code:
    public class Exit {
    	
    	private String dir;
    	private Room dest;
    	public static int exitAmount;
    	
    	public Exit(String dir, Room dest){
    		this.dir = dir;
    		this.dest = dest;
    		exitAmount += 1;
    	}
    	
    	public String getDir(){
    		return dir;
    	}
    	
    	public Room getDest(){
    		return dest;
    	}
    }
    Java Code:
    public class Player {
    	
    	private String name;
    	private Room currLocation;
    	
    	public Player(String name, Room currLocation){
    		this.name = name;
    		this.currLocation = currLocation;
    		System.out.println("Welcome " + name);
    	}
    	
    	public Room getLocation(){
    		return currLocation;
    	}
    	
    	public void setLocation(Room currLocation){
    		this.currLocation = currLocation;
    	}
    }
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    exit cannot be resolved

    at Practice.main(Practice.java:44)

  7. #7
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    760
    Rep Power
    8

    Default Re: How do I cycle through objects, then use a method from the found object?

    The "exit" variable is local to the previous for-loop. It will only exists in the for-loop. When the loop is finish this variable will be gone.

  8. #8
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    I figured as much, but I don't know how to fix it. m(_ _)m

  9. #9
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    Java Code:
    import java.util.*;
    
    public class Practice{
    	
    	private static String name;
    	private static Room currLocation;
    	static String[] dirName = {"north", "south", "east", "west"};
    	static String[] shortDirName = {"n", "s", "e", "w"};
    	Vector exits = new Vector();
    	static Scanner sc = new Scanner(System.in);
    	
    	public static void main(String[] args) {
    
    		System.out.print("What is your name? ");
    		name = sc.nextLine();
    		
    		//Make rooms
    		Room test = new Room("Sup", "This is test room");
    		Room otherRoom = new Room("Sup", "This is test room 2");
    		
    		//Create player object
    		Player player = new Player(name, test);
    		player.setLocation(test);
    		currLocation = test;
    		
    		//Make exits
    		test.addExit(new Exit("north", otherRoom));
    		otherRoom.addExit(new Exit("south", test));
    		
    		//Show location info
    		showLocation(player);
    		
    		//Setup input and read it for dirs
    		String input = sc.nextLine();
    		input = input.toLowerCase();
    		currLocation = player.getLocation();
    		checkDir(player, input);
    		
    	}
    
    	public static void showLocation(Player player) {
    		System.out.println(currLocation.getTitle());
    		System.out.println(currLocation.getDesc());
    		for(Enumeration e = currLocation.getExits().elements(); e.hasMoreElements();){
    			Exit exit = (Exit)e.nextElement();
    		}
    		Scanner sc = new Scanner(System.in);
    		String input = sc.nextLine();
    		input = input.toLowerCase();
    		checkDir(player, input);
    	}
    	
    	public static void checkDir(Player player, String input){
    		
    		for(int x = 0; x < dirName.length; x++){
    			
    			if(input.equals(dirName[x]) || input.equals(shortDirName[x])){
    				
    				for(Enumeration e = currLocation.getExits().elements(); e.hasMoreElements();){
    					Exit exit = (Exit)e.nextElement();
    					currLocation = exit.getDest();
    					player.setLocation(currLocation);
    					showLocation(player);
    				}
    			}
    		}
    	}
    }
    Java Code:
    import java.util.*;
    
    public class Room {
    	
    	private String title;
    	private String desc;
    	public static int roomAmount;
    	Vector vecExits = new Vector();
    	
    	public Room(String title, String desc){
    		this.title = title;
    		this.desc = desc;
    		roomAmount += 1;
    	}
    	
    	public String getTitle(){
    		return title;
    	}
    	
    	public String getDesc(){
    		return desc;
    	}
    	
    	public void addExit(Exit exit){
    		vecExits.addElement(exit);
    	}
    	
    	public void removeExit(Exit exit){
    		if(vecExits.contains(exit)){
    			vecExits.removeElement(exit);
    		}
    	}
    	
    	public Vector getExits (){
    		return (Vector)vecExits.clone();
    	}
    }
    Java Code:
    ublic class Exit {
    	
    	private String dir;
    	private Room dest;
    	public static int exitAmount;
    	
    	public Exit(String dir, Room dest){
    		this.dir = dir;
    		this.dest = dest;
    		exitAmount += 1;
    	}
    	
    	public String getDir(){
    		return dir;
    	}
    	
    	public Room getDest(){
    		return dest;
    	}
    }
    Java Code:
    public class Player {
    	
    	private String name;
    	private Room currLocation;
    	
    	public Player(String name, Room currLocation){
    		this.name = name;
    		this.currLocation = currLocation;
    		System.out.println("Welcome " + name);
    	}
    	
    	public Room getLocation(){
    		return currLocation;
    	}
    	
    	public void setLocation(Room currLocation){
    		this.currLocation = currLocation;
    	}
    }
    this compiles at least, but doesn't work in the slightest, as long as I type in a correct dir, it just swaps rooms, and there has to be a better way to do this than throwing the player object around.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I cycle through objects, then use a method from the found object?

    Again, since direction is such a key concept, and since it will likely never be modified, I would use an enum for this, something like,

    Java Code:
    enum MyDirection {
       NORTH("north", "n"), SOUTH("south", "s"), EAST("east", "e"), WEST("west", "w");
       
       private String dirName;
       private String shortDirName;
       private MyDirection(String dirName, String shortDirName) {
          this.dirName = dirName;
          this.shortDirName = shortDirName;
       }
       public String getDirName() {
          return dirName;
       }
       public String getShortDirName() {
          return shortDirName;
       }
       
    }
    Again Player would know its own Room, and when it wants to move to a new room, it needs to interact with its own room to do so. I would give the Player class a boolean method like move(MyDirection dir), that asks the Room if it can move in a certain direction, and if so then it moves there. If it succeeds at moving it returns true, else it returns false. Something like:

    Java Code:
       public boolean move(MyDirection dir) {
          // first ask room if it is possible to move in direction
          if (room.canMove(dir)) {
             //if so, then move into new room
             room = room.move(dir);
             return true; 
          } else {
             // else stay where we are and return false
             return false;
          }
       }
    Of course Room would need its own boolean canMove(MyDirection dir) and a move(MyDirection dir) method the latter of which returns the Room that the Player is moving into.

    Room could possibly have an EnumMap<MyDirection, Room> or some such to hold the connecting Rooms and relate them to the MyDirection enum. You could have the Map hold Door objects instead and have this class hold a field for the other Room and also has a boolean open field, allowing the Door to be open or closed.
    Last edited by Fubarable; 12-03-2012 at 05:45 PM.

  11. #11
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    But even with new methods, I still would have problems with getting the correct dir before calling the methods with it.
    Java Code:
    for(Enumeration e = currLocation.getExits().elements(); e.hasMoreElements();){
                        Exit exit = (Exit)e.nextElement();
    }
    only picks the last one, I thought it would pick the one which dir is the same as the dir the player inputted.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I cycle through objects, then use a method from the found object?

    Quote Originally Posted by Darkzombies View Post
    But even with new methods, I still would have problems with getting the correct dir before calling the methods with it.
    Java Code:
    for(Enumeration e = currLocation.getExits().elements(); e.hasMoreElements();){
                        Exit exit = (Exit)e.nextElement();
    }
    only picks the last one, I thought it would pick the one which dir is the same as the dir the player inputted.
    I'm not sure I understand what you mean here. Can you elaborate?

  13. #13
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    Ok, let's say the player inputs "North" and the only available path is south, they would still go to the room to the south, it doesn't get the correct dir. If I don't have the correct dir, I cannot call player.move(MyDirection dir) also, I don't understand enums all to well, so I'm going to go find a tutorial :3
    Last edited by Darkzombies; 12-03-2012 at 06:42 PM.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I cycle through objects, then use a method from the found object?

    Quote Originally Posted by Darkzombies View Post
    Ok, let's say the player inputs "North" and the only available path is south, they would still go to the room to the south, it doesn't get the correct dir.
    If you implemented my suggestions, your player would call move(MyDirection.NORTH) and this would return false since the Room object it holds would return false when you call room.canMove(MyDirection.NORTH). If this isn't working, then you're not implementing my recommendations correctly and will need to show us your attempt.

    If I don't have the correct dir, I cannot call player.move(MyDirection dir) also, I don't understand enums all to well, so I'm going to go find a tutorial :3
    Yes, finding a tutorial on enums would be a great idea.

  15. #15
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    I think I'm starting to understand all this, but how do I find out what to put into the move(MyDirection.SOMETHING) Would I have to do
    Java Code:
    if(input.equals("north")){
    move(MyDirection.NORTH)
    }
    or is there a more reasonable way of doing it?

    actually, it would probably be
    Java Code:
    if(input.equals(MyDirection.NORTH)){
    move(MyDirection.NORTH)
    }
    but it still is probably not the best way.
    Last edited by Darkzombies; 12-04-2012 at 01:08 AM.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I cycle through objects, then use a method from the found object?

    Your way could work of course. Another possible way is to use the enum method valueOf(String str), something like:

    Java Code:
    MyDirection dir = MyDirection.valueOf(input.toUpperCase());
    But this can be a bit kludgy because if the user enters a bad String, such as n or southeast, this will throw an IllegalArgumentException, and this can be caught of course, but this technique is completely dependent on the name of the enum which doesn't smell like a good design to me.

    Another option is to present the user with a menu asking them to enter a number for the direction, or a letter. However you do this, you'll need to check for bad input and act accordingly. But also however you do it, you will want to design your non-user interface classes for maximal flexibility with an eye towards using them in a GUI version down the road. Your console interface should be flexible too of course, but it will likely get discarded down the road.

  17. #17
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    By GUI, you mean using the JOptionPane class? Cause I don't believe I even know how to get input from those, I guess I could look it up later on.
    Last edited by Darkzombies; 12-04-2012 at 02:59 AM.

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I cycle through objects, then use a method from the found object?

    Quote Originally Posted by Darkzombies View Post
    Ok, so I could probably either do a switch or a bunch of else if's to do the input, and by GUI, you mean using the JOptionPane class? Cause I don't believe I even know how to get input from those, I guess I could look it up later on.
    No, most users will find using swapping JOptionPanes worse than using a console program. No I mean a full-fledged Swing or JavaFX2 GUI. Or even Android. The core classes constitute your program's "model" and they need to be flexible and user-interface agnostic, meaning they should have no user interface code in them and shouldn't care what UI is used to run the program. So classes like Player, Room, enums like Direction should have no Scanner objects included.

  19. #19
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I cycle through objects, then use a method from the found object?

    Ok, so, hopefully, final question: How would I check the input against the four directions, and the directions the exits are in. I attempted to do it myself, but quickly got stuck.
    Java Code:
    	public static void checkDir(Player player, String input){
    		
    		for(Enumeration e = currLocation.getExits().elements(); e.hasMoreElements();){
    			
    			if(input.equals(myDirection.NORTH) || input.equals("N")){
    				player.move(myDirection.NORTH);
    			}
    		
    			if(input.equals(myDirection.SOUTH) || input.equals("S") && e.getDir().equals(myDirection.NORTH)){
    				player.move(myDirection.SOUTH);
    			}
    		
    			if(input.equals(myDirection.EAST) || input.equals("E")){
    				player.move(myDirection.EAST);
    			}
    		
    			if(input.equals(myDirection.WEST) || input.equals("W")){
    				player.move(myDirection.WEST);
    			}
    			e.nextElement();
    		}
    		showLocation(player);
    	}

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: How do I cycle through objects, then use a method from the found object?

    If you have an enum you can do some nice things with it, for example a getValue(String) static method (instead of using the default valueOf()).
    This would allow you to move the user input checking code, mostly, out of there.
    So, using Fubarable's example above with the dirName and shortDirName, you could add a static method to the enum that checks both against a supplied String, and returns null if it's invalid.
    Java Code:
    public static MyDirection getValue(String input) {
        for (MyDirection dir : values()) {
            if (dir.dirName.equals(input) || dir.shortDirName.equals(input)) {
                return dir;
            }
        }
        return null;  // or maybe throw an exception?  Up to you
    }
    That takes your above code out and allows you to add extra directions with minimal changes to the code.

    You now need to figure out what you plan on doing when they enter an incorrect direction (as in entirely invalid, so the above returns null).
    And then figure out what to do if they enter a valid direction (as in a valid enum) that is invalid in the room itself.

    The idea behind writing it like this is to break the problem down into the smallest parts possible.
    So the whole direction thing had various really small sub-problems.
    First how to model the directions, which Fubarable showed by using an enum.
    Then how to map the user input to the enum, which is a mix of Fubarable's enum with the two forms, and the getValue() method above.
    Then what to do with an invalid entry, as in there is no enum for that input.
    Then what to do for a valid enum that isn't a valid direction in the room.

    Baby steps.
    Fubarable likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Page 1 of 3 123 LastLast

Similar Threads

  1. Main Method not found in class
    By HinaKhan in forum New To Java
    Replies: 6
    Last Post: 06-22-2012, 02:34 PM
  2. Symbol not found - object invisible outside of class
    By stesteve in forum New To Java
    Replies: 5
    Last Post: 02-15-2012, 09:57 PM
  3. Method not found
    By fleg in forum New To Java
    Replies: 8
    Last Post: 10-12-2010, 05:02 PM
  4. incompatible types found object expect integer
    By bflhr673 in forum New To Java
    Replies: 3
    Last Post: 07-24-2010, 03:10 PM
  5. JButtonGroup; add() method not found?
    By Moddy in forum AWT / Swing
    Replies: 3
    Last Post: 10-15-2008, 11:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •