Page 2 of 3 FirstFirst 123 LastLast
Results 21 to 40 of 44
Like Tree1Likes

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

  1. #21
    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?

    So wait, do I put
    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
    }
    in my main class? I don't think that will compile. Heres my full code so far, for reference.

    Java Code:
    import java.util.*;
    
    public class Practice{
    	
    	private static String name;
    	private static Room currLocation;
    	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("Library", "A dark library illuminated by flickering candles. \nHuge dusty bookshelves line the floor. \nTo the north a steel door beckons.");
    		Room otherRoom = new Room("Dark Hallway", "A long passage looms ahead, or what seems to be one. \nYou cannot see the end of the corridor. \nThe door behind you is no longer there.");
    		
    		//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() + "\n");
    		System.out.println(currLocation.getDesc());
    		Scanner sc = new Scanner(System.in);
    		String input = sc.nextLine();
    		input = input.toLowerCase();
    		currLocation = player.getLocation();
    		checkDir(player, input);
    		sc.close();
    	}
    	
    	public static void checkDir(Player player, String input){
    					//will be gone soon
    		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")){
    				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);
    	}
    }
    Java Code:
    import java.util.Vector;
    
    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();
    	}
    	
    	public static boolean canMove(myDirection dir){
    		return true;
    	}
    
    	public static void move(myDirection dir) {
    		
    	}
    }
    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 + "\n");
    	}
    	
    	public Room getLocation(){
    		return currLocation;
    	}
    	
    	public void setLocation(Room currLocation){
    		this.currLocation = currLocation;
    	}
    	
    	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.move(dir);
    		      return true; 
    		   } else {
    		      // else stay where we are and return false
    			   System.out.println("\nInvalid Direction! Returning to room\n");
    		      return false;
    		   }
    		}
    }
    Java Code:
    	
    public 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;
    		   }
    		    
    	}

  2. #22
    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?

    So uhh, I never really asked, but how would I start up the myDirection
    Java Code:
    myDirection dir = new myDirection("How do I get all dirs in one String?");

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

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

    First off, classes and enums begin with a capital letter. Please get in this habit so that others (us!) don't have to struggle analyzing your code. Next of all, if MyDirection is an enum, then you don't call a constructor. You just set it. e.g.,:

    Java Code:
    MyDirection dir = MyDirection.NORTH;

  4. #24
    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 in the method he gave he, it uses MyDirection dir, and obviously that won't compile because it was never defined. Not to mention it doesn't hold an array of all the constants. Although there may be a way to cycle through them. When I get code that can't even compile it confused me, then I start to overthink it, then I just get all burnt out.

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

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

    Quote Originally Posted by Darkzombies View Post
    But in the method he gave he,...
    What method who gave you?

    ... it uses MyDirection dir, and obviously that won't compile because it was never defined.
    Don't say obviously, at least not yet. If you're talking about the MyDirection enum, yes it was fully defined.

    Not to mention it doesn't hold an array of all the constants.
    If it's an enum, then yes it does, in the values() method.

    Although there may be a way to cycle through them. When I get code that can't even compile it confused me, then I start to overthink it, then I just get all burnt out.
    If you get code that won't compile and you're in an active discussion with us about this, then consider showing it to us along with any compilation errors.

  6. #26
    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?

    Hmm, so, if I use the .values(), I probably can't do
    Java Code:
    for(int x = 0; x < MyDirection.values(); x++){
    			
    		}
    and I did a tutorial on for each loops, but I couldn't completely understand it, all I got from it was for(String x : n){ was like "for x in n" or something, which confused me more. There's lots of stuff about this that confuses me. Probably because I'm not used to OOP

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

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

    Quote Originally Posted by Darkzombies View Post
    Hmm, so, if I use the .values(), I probably can't do

    Java Code:
    for(int x = 0; x < MyDirection.values(); x++){
    			
    }
    and I did a tutorial on for each loops, but I couldn't completely understand it, all I got from it was for(String x : n){ was like "for x in n" or something, which confused me more. There's lots of stuff about this that confuses me. Probably because I'm not used to OOP
    You don't need a for-each loop if you don't want to use one (though they can be handy, and I suggest you learn more about them). Just remember that values() returns an array object, and just like any array object, it will have a length field that you can use. So this is valid and often done:

    Java Code:
    for(int x = 0; x < MyDirection.values().length; x++){
       MyDirection dir = MyDirection.values()[x];
    
       // .... do something with dir here
    
    }

  8. #28
    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:
    	public static void getDir(Player player, String input){
    		for(int x = 0; x < MyDirection.values().length; x++){
    			for(Enumeration e = currLocation.getExits().elements();e.hasMoreElements()){
    			   MyDirection dir = MyDirection.values()[x];
    			   String exitDir = currLocation.getExits().
    			   if(input.equals(dir) && input.equals(exitDir)){
    				   player.move(dir);
    			   }
    			}
    		}
    	}
    How would I use a method from all Exits available in that room to get the direction and destination of that exit in the current room? The "e" variable can't use Exits methods because it is only the Vector.

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

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

    Please clarify. What is this static getDir method supposed to be doing? And why static?

  10. #30
    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?

    getDir is just a method I am using for checking everything then sending it off to player.move(), and I have no idea why It's static xD, I'll fix that. EDIT: hmm okay maybe not, I have to call the methods from the main method, so I'm not sure how to avoid using statics in that case.
    Last edited by Darkzombies; 12-05-2012 at 06:09 AM.

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

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

    Still please explain what that code above is supposed to do. Please remember that we are not as well versed on your program as you are, and so we can't glance at a portion of code and know easily what its purpose is.

    I will be going to bed soon, so if you need my help please explain this. Else hopefully someone else will jump on board with this.

  12. #32
    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:
    public static void getDir(Player player, String input){ //the input is originally asked for in the main 
        //method before coming here
    
        for(int x = 0; x < MyDirection.values().length; x++){ //Start a loop to go through all of MyDirections 
        //constants
    
            for(Enumeration e = currLocation.getExits().elements();e.hasMoreElements()){ //go through all the 
            //Exits stored in the vector of the room the player is currently in.
    
               MyDirection dir = MyDirection.values()[x]; //Puts the constants in a variable
    
               String exitDir = currLocation.getExits().getDir(); //Attempts to get the Dirs of all 
               //exits in the room, fails horribly.
    
               if(input.equals(dir) && input.equals(exitDir)){ //checks if input equals the constants of MyDirection 
               //and the correct direction of the exits.
    
                   player.move(dir); //calls the move function in Player.
    
               }
            }
        }
        showLocation(); //goes to a function that displays room data, and prompts the user for the next direction.
    }
    Last edited by Darkzombies; 12-05-2012 at 06:21 AM.

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

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

    I would go about that somewhat differently. One way is to create a movePlayer method that accepts a Player object and prompts it for a direction String. This is for a console app only.

    Java Code:
    public void movePlayer(Player player) {
      boolean moveOK = false;
      while (!moveOK) {
        String dirString = promptPlayerForDirection(Player);
        try {
          MyDirection dir = getMyDirFromString(dirString);
          if (player.move(dir)) { // if Room has exit, this moves Player and returns true
            moveOK = true; // or return
          } else {
            // warn Player that Room doesn't have this exit, to try another
          }
        } catch (InvalidMyDirectionStringException e) {
          // warn player that direction String dirString was not valid
        }
      }
    }
    This would call a method, getMyDirFromString that tries to translate a String into a MyDirection object using the Strings held by MyDirection objects.:

    Java Code:
    public MyDirection getMyDirFromString(String dirString) throws InvalidMyDirectionStringException {
      for (MyDirection dir: MyDirection.values){
         if (dir.getDirName().equalsIgnoreCase(dirString) || dir.getShortDirName().equalsIgnoreCase(dirString)) {
           return dir;
         }
      }
      // if were here, then no dir was found
      throw new InvalidMyDirectionStringException(dirString);
    }
    If no valid String is found, then you could have the above method throw an exception

    Java Code:
    public class InvalidMyDirectionStringException extends Exception {
      public InvalidMyDirectionStringException(String text) { 
        super(text);
      }
    }

  14. #34
    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?

    Hmm, this is helpful for the most part, it gets rid of all attempts to get the dir from the exits. But I would still have to get the destination from all exits, more specifically, the one chosen by the user in order to move the player. Which again, is probably the entire point of this thread in the first place. For 2 pages I've been trying to figure this out: How can
    Java Code:
    for(Enumeration e = currLocation.getExits().elements();e.hasMoreElements;){
    be used/modified to be able to access the methods of the elements (which consists of Exit objects) and in turn be able to find the directions and destinations of all exits in the current location of player.

  15. #35
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

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

    The method I wrote earlier (and the similar one Fubarable has) belong with the enum.
    At least in my opinion, hence the reason I made it static.
    Please do not ask for code as refusal often offends.

  16. #36
    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 kinda figured that myself after a bit of thinking, but what I really need help on (It was the original point of this thread, hopefully we can end it with an answer) is:

    how do I access the methods of the elements (which consists of Exit objects) and in turn be able to find the directions and destinations of all exits in the current location of player in order to complete player.move() and/or room.move() functions.

  17. #37
    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?

    Hmm, well for the time being, I'm going to try other methods besides Vectors. Maybe Lists or Maps or LinkedLists.

  18. #38
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

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

    You need to use generics.
    So your List (Vector was superceded by List years ago, which I forgot to mention) would be:
    Java Code:
    List<Exit> exits = new ArrayList<Exit>;
    So when you get() the exit from a list it will be an Exit object (as far as the compiler is concerned).
    In fact, as you seem to be thinking, a Map<MyDirection, Exit> might be better, as far as a Room is concerned.
    This will allow you to easily get at a relevant Exit.
    Please do not ask for code as refusal often offends.

  19. #39
    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 almost done, but for some reason Room.canMove() isn't coming back true, even though it should be.

    WARNING: LOTS OF CODE

    Java Code:
    import java.util.*;
    
    public class Practice{
    	
    	private static String name;
    	private static Room currLocation;
    	List<Exit> exits = new ArrayList<Exit>();
    	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("Library", "A dark library illuminated by flickering candles. \nHuge dusty bookshelves line the floor. \nTo the north a steel door beckons.");
    		Room otherRoom = new Room("Dark Hallway", "A long passage looms ahead, or what seems to be one. \nYou cannot see the end of the corridor. \nThe door behind you is no longer there.");
    		
    		//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);
    
    	}
    
    	public static void showLocation(Player player) {
    		
    		System.out.println("\n" + currLocation.getTitle() + "\n");
    		System.out.println(currLocation.getDesc());
    		
    		currLocation = player.getLocation();
    		movePlayer(player);
    	}
    	
    	public static void movePlayer(Player player) {
    		  boolean moveOK = false;
    		  while (!moveOK) {
    		    String dirString = promptPlayerForDirection();
    		    try {
    		      MyDirection dir = getMyDirFromString(dirString);
    		      if (player.move(dir)) { // if Room has exit, this moves Player and returns true
    		        moveOK = true; // or return
    		        currLocation = player.getLocation();
    		        showLocation(player);
    		      } else {
    		        // warn Player that Room doesn't have this exit, to try another
    		    	  System.out.print("Current location has no " + dirString + " exit.");
    		      }
    		    } catch (InvalidMyDirectionStringException e) {
    		      // warn player that direction String dirString was not valid
    		    	System.out.println("Not a valid direction!");
    		    	e.printStackTrace();
    		    }
    		}
    		showLocation(player);
    	}
    	
    	private static String promptPlayerForDirection() {
    		Scanner sc = new Scanner(System.in);
    		System.out.print("Type a direction: ");
    		String input = sc.nextLine();
    		return input;
    	}
    
    	public static MyDirection getMyDirFromString(String dirString) throws InvalidMyDirectionStringException {
    		  for (MyDirection dir: MyDirection.values()){
    		     if (dir.getDirName().equalsIgnoreCase(dirString) || dir.getShortDirName().equalsIgnoreCase(dirString)) {
    		       return dir;
    		     }
    		  }
    		  // if were here, then no dir was found
    		  throw new InvalidMyDirectionStringException(dirString);
    	}
    }
    Java Code:
    import java.util.*;
    
    
    public class Room {
    	
    	private String title;
    	private String desc;
    	public static int roomAmount;
    	private List<Exit> exits = new ArrayList<Exit>();
    	
    	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){
    		exits.add(exit);
    	}
    	
    	public void removeExit(Exit exit){
    		if(exits.contains(exit)){
    			exits.remove(exit);
    		}
    	}
    	
    	public List<Exit> getExits (){
    		return exits;
    	}
    	
    	public static boolean canMove(MyDirection dir, Room currLocation){
    		System.out.println("Inside Room.canMove");
    		boolean temp = false;
    		for(ListIterator<Exit> e = currLocation.getExits().listIterator();e.hasNext();){
    			if(e.hasNext()){
    				temp = true;
    			}
    		}
    		return temp;
    	}
    
    	public static void move(MyDirection dir, Room currLocation) {
    		System.out.println("Inside Room.move");
    		for(ListIterator<Exit> e = currLocation.getExits().listIterator();e.hasNext();){
    			Room dest = e.next().getDest();
    		}
    	}
    }
    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 + "\n");
    	}
    	
    	public Room getLocation(){
    		return currLocation;
    	}
    	
    	public void setLocation(Room currLocation){
    		this.currLocation = currLocation;
    	}
    	
    	public boolean move(MyDirection dir) {
    			System.out.println("Inside player.move");
    		   // first ask room if it is possible to move in direction
    		   if (Room.canMove(dir, currLocation)) {
    		      //if so, then move into new room
    			   System.out.println("Never get this message.");
    			   //It should be returning true
    		      Room.move(dir, currLocation);
    		      return true; 
    		   } else {
    		      // else stay where we are and return false
    			   System.out.println("\nInvalid Direction! Returning to room\n");
    		      return false;
    		   }
    		}
    }
    Java Code:
    	
    public 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;
    		   }
    		   public static MyDirection getValue(String input) {
    			    for (MyDirection dir : values()) {
    			        if (dir.dirName.equals(input) || dir.shortDirName.equals(input)) {
    			            return dir;
    			        }
    			    }
    			    return null;
    			}
    		    
    	}
    Java Code:
    public class InvalidMyDirectionStringException extends Exception {
      public InvalidMyDirectionStringException(String text) { 
        super(text);
      }
    }
    Last edited by Darkzombies; 12-07-2012 at 02:22 AM.

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

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

    You'd better add more println's to see if you're stuck in some method (hint).

    You're also still using Strings to store directional information, and that's not a good thing. That is what the enum is for.
    Last edited by Fubarable; 12-07-2012 at 03:06 AM.

Page 2 of 3 FirstFirst 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
  •