Google Answers Logo
View Question
 
Q: Java toString() and no value return problem ( No Answer,   4 Comments )
Question  
Subject: Java toString() and no value return problem
Category: Computers > Programming
Asked by: drunkpanda-ga
List Price: $6.00
Posted: 05 Apr 2005 21:35 PDT
Expires: 05 May 2005 21:35 PDT
Question ID: 505572
Hi i have two problems please help me 

if you take look the "Game Class" -> "take" method

     System.out.println(theItems);

the first problem is: the above method return the value like this:
Item@f9c40, and i know i have to use toString() method but i have used
the method for something else (currentPlayer.getName();)

     System.out.println(currentPlayer.getMyCarriedWeight());

the second problem is: the above method which did n't catch any value.
I really don't know what to do because each class complied profectly
ok with no errors in it

there are totally 7 classes but i only display 3 of them as showing below 

thank you very much 
Drunkpanda 

--------------- Game Class -----------------
import java.util.ArrayList;
public class Game 
{
    private Parser parser;
    private Room currentRoom;
    private Player currentPlayer;
    private ArrayList visitedRooms;
    private Item currentItem;
   
   
        
    /**
     * Create the game and initialise its internal map.
     */
    public Game() 
    {
        createRooms();
        parser = new Parser();
        visitedRooms = new ArrayList();
        currentPlayer = new Player("Mark",currentRoom);
    }
    
    /**
     * Create all the rooms and link their exits together.
     */
    private void createRooms()
    {
        Room outside, theatre,office, cafeteria, library, bookstore,
tutorial, NBlack, lab,SBlack2,SBlack3, examRoom;
      
        // create the rooms
        outside = new Room("outside the main entrance of the
Polytechnic","textbook");
        theatre = new Room("in a lecture theatre","threatre");
        cafeteria = new Room("in the cafeteria","cafeteria");
        library = new Room("in a campus library","library");
        office = new Room("in the computing admin office","office");
        lab = new Room("in the second level of N black in lab class","lab");
        bookstore = new Room("in the bookstore","bookstore");
        tutorial = new Room("in the tutorial class","tutorial");
        NBlack = new Room("in the outside of N Block", "NBlack");
        SBlack2 = new Room("in the second level of S black","SBlack2");
        SBlack3 = new Room("in the third level of S black","SBlack3");
        examRoom = new Room("in the Exam Room","examRoom");
        // initialise room exits
        outside.setExit("east", theatre);
        outside.setExit("south", library);
        outside.setExit("west", cafeteria);

        theatre.setExit("west", outside);
        theatre.setExit("east",office);
        theatre.setExit("up", lab);
        
        lab.setExit("down",theatre);
        
        office.setExit("west", theatre);
        office.setExit("south", NBlack);
        office.setExit("up", SBlack2);
        
        SBlack2.setExit("up", SBlack3);
        SBlack2.setExit("down", office);
        
        SBlack3.setExit("east", examRoom);
        SBlack3.setExit("down", SBlack2);
        
        examRoom.setExit("west",SBlack3);

        cafeteria.setExit("east", outside);
        cafeteria.setExit("west", bookstore);
        bookstore.setExit("east", cafeteria);

        library.setExit("north", outside);
        library.setExit("south", tutorial);
            
        tutorial.setExit("north", library);
        tutorial.setExit("east",NBlack);
        
        NBlack.setExit("west",tutorial);
        NBlack.setExit("north",office);
                
        currentRoom = outside;  // start game outside
        
        // add items 
        //moveable items
        Item textbook = new Item("this is a Java textbook","textbook",100,true);
        library.addItem(textbook);
        Item dictionary = new Item("this is a eletronic
dictionary","dictionary",20,true);
        bookstore.addItem(dictionary);
        Item form = new Item("This is a exam application form","form",20,true);
        office.addItem(form);
        Item exam = new Item("this is a exam paper","exam",20,true);
        examRoom.addItem(exam);
        Item answer = new Item("you just see a answer sheet on the
grass","answer",20,true);
        NBlack.addItem(answer);
        //unmoveable items
        Item pancake = new Item("there is a pancake on table","pancake",20,false);
        cafeteria.addItem(pancake);
        Item watch = new Item("there is a watch beside a
computer","watch",20,false);
        tutorial.addItem(watch);
        Item cellphone = new Item("there is a cellphone on
table","cellphone",20,false);
        theatre.addItem(cellphone);
    }

    /**
     *  Main play routine.  Loops until end of play.
     */
    public void start() 
    {            
        printWelcome();

        // Enter the main command loop.  Here we repeatedly read commands and
        // execute them until the game is over.
                
        boolean finished = false;
        while (! finished) {
            Command command = parser.getCommand();
            finished = processCommand(command);
        }
        System.out.println("I will see you next time");
        System.out.println("Thank you for playing.  Good bye.");
    }
    
     /**
      * overrides Object's toString method
      */
    public String toString() 
     {
        String thePlayer = currentPlayer.getName();    
        return thePlayer;
    }
   
    /**
     * Print out the opening message for the player.
     */
    private void printWelcome()
    {
        System.out.println("Hi "+toString()+" Welcome to the CPIT, City Campus!");
        System.out.println(" City Campus is a new, incredibly boring
adventure game.");
        System.out.println("Type 'help' if you need help.");
        System.out.println();
        System.out.println(currentRoom.getLongDescription());
    }

    /**
     * Given a command, process (that is: execute) the command.
     * If this command ends the game, true is returned, otherwise false is
     * returned.
     */
    private boolean processCommand(Command command) 
    {
        boolean wantToQuit = false;

        if(command.isUnknown()) {
            System.out.println("I don't know what you mean...");
            return false;
        }

        String commandWord = command.getCommandWord();
        if (commandWord.equals("help"))
            printHelp();
        else if (commandWord.equals("go"))
            goRoom(command);
        else if (commandWord.equals("look"))
            look(command);
        else if (commandWord.equals("take"))
            take(command);
        else if (commandWord.equals("drop"))
            drop(command);
        else if (commandWord.equals("back"))
            goBack(command);        
        else if (commandWord.equals("quit")){
            wantToQuit = quit(command);
        }
        return wantToQuit;
    }

    // implementations of user commands:

    /**
     * Print out some help information.
     * Here we print some stupid, cryptic message and a list of the 
     * command words.
     */
    private void printHelp() 
    {
        System.out.println("You are lost. You are alone. You wander");
        System.out.println("around at the Polytechnic.");
        System.out.println("How to play?");
        System.out.println();
        System.out.println("Your command words are:");
        parser.showCommands();
    }

    /** 
     * Try to go to one direction. If there is an exit, enter the new
     * room, otherwise print an error message.
     */
    private void goRoom(Command command) 
    {
        if(!command.hasSecondWord()) {
            // if there is no second word, we don't know where to go...
            System.out.println("Go where?");
            return;
        }
        String direction = command.getSecondWord();
        // Try to leave current room.
        Room nextRoom = currentRoom.getExit(direction); 
        
        if (nextRoom == null)
            System.out.println("There is no door!");
        else {   
            currentRoom = nextRoom;
            visitedRooms.add(currentRoom);
            System.out.print(toString()+"," +currentRoom.getLongDescription());
        }  
        
    }
    
    /** 
     * "Quit" was entered. Check the rest of the command to see
     * whether we really quit the game. Return true, if this command
     * quits the game, false otherwise.
     */
    private boolean quit(Command command) 
    {
        if(command.hasSecondWord()) {
            System.out.println("Quit what?");
            return false;
        }
        else
            return true;  // signal that we want to quit
    }
    /**
     * "Look" was entered. look around if there is any item in a room 
     */
    private void look(Command command)
    {
        System.out.println(currentRoom.getMyItemsDescription());
    }
    
    /**
     * "Take" was entered. take a item in a room, if there is any
     */
    private void take(Command command)
    {
      String theItem = command.getSecondWord();
        Item theItems = currentRoom.getItem(theItem);
        
            if (!command.hasSecondWord())
            {
                System.out.println("Take what?");
            return;
            }
            // check if the typed item name is recognized
            if (theItems == null)
            {
               System.out.println("This is not a correct item name");
              return;
            }
            System.out.println(theItems);
            System.out.println(currentPlayer.getMyCarriedWeight());
            
            if(currentPlayer.getMyCarriedWeight() +
theItems.getWeight() > currentPlayer.getMaxWeight()){
                System.out.println("This Item is too heavy for you to carry!");
            return;
            }
            if(theItems.isMoveable()){ 
                System.out.println("You can't move the item");
            return;
            }
            
            currentPlayer.addItem(theItems);
            System.out.println("The item has been taken");
            currentRoom.removeItem(theItems);
    }
    
     private void drop(Command command)
   {
        String theItem = command.getSecondWord();
        Item theItems = currentPlayer.getItem(theItem);
        
        if (!command.hasSecondWord()){
                System.out.println("Drop what?");
            return;
            }
            // check if the typed item name is recognized
        if (theItems == null)
            {
               System.out.println("This is not a correct item name or
you havn't actually taken the item yet");
              return;
            }
        
        currentPlayer.removeItem(theItems);
        System.out.println("the item has dropped");
        currentRoom.addItem(theItems);
   }
   
    /**
     * Go back to the previous room.
     */
    private void goBack(Command command)
    {
        if (visitedRooms.isEmpty())
            System.out.println("Oops No more, you can only go back to
the room you just pass by");
        else {
            currentRoom = (Room)visitedRooms.get(visitedRooms.size()-1);
            visitedRooms.remove(visitedRooms.size()-1);
            System.out.println(currentRoom.getLongDescription());
        }
    }

  
}
---------------- Room Class ------------------------------
import java.util.Set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.HashSet;
public class Room 
{
    private String description;
    private HashMap exits;        // stores exits of this room.
    private String name;
    private HashSet myItems;
 

    /**
     * Create a room described "description". Initially, it has no exits.
     * "description" is something like "in a kitchen" or "in an open court 
     * yard".
     */
    public Room(String description, String name) 
    {
        this.description = description;
        this.name = name;
        exits = new HashMap();
        myItems = new HashSet();
       
    }

    /**
     * Define an exit from this room.
     */
    public void setExit(String direction, Room neighbor) 
    {
        exits.put(direction, neighbor);
    }
    

    /**
     * Return the description of the room (the one that was defined in the
     * constructor).
     */
    public String getShortDescription()
    {
        return description;
    }

    /**
     * Return a long description of this room, in the form:
     *     You are in the kitchen.
     *     Exits: north west
     */
    public String getLongDescription()
    {
        return "You are " + description + ".\n" + getExitString();
    }

    /**
     * Return a string describing the room's exits, for example
     * "Exits: north west".
     */
    private String getExitString()
    {
        String returnString = "Exits:";
        Set keys = exits.keySet();
        for(Iterator iter = keys.iterator(); iter.hasNext(); )
            returnString += " " + iter.next();
        return returnString;
    }

    /**
     * Return the room that is reached if we go from this room in direction
     * "direction". If there is no room in that direction, return null.
     */
    public Room getExit(String direction) 
    {
        return (Room)exits.get(direction);
    }
    
    /**
     * Add items to the rooms
     */
    public void addItem(Item myItem)
    {
        myItems.add(myItem);
    }
    public void removeItem(Item myItem)
    {
        myItems.remove(myItem);
    }
    public Item getItem(String theItem)
    {
        Iterator iter = myItems.iterator();
        while(iter.hasNext())
        {
            Item anItem = (Item) iter.next();
            if(anItem.getName().equals(theItem))
            return anItem;
        }
        return null;
    }
    public String getMyItemsDescription()
    {
        String returnString = "This room has items:";
        for(Iterator iter = myItems.iterator(); iter.hasNext();)
            returnString += " "+ ((Item)iter.next()).getDescription();
        return returnString;
    }
    public String getName()
    {
        return name;
    }
}
--------------------- Item Class ---------------------
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;


public class Item
{
    private String description;
    private String name;
    private int weight;
    private boolean moveable;


    /**
     * Constructor for objects of class Item.
     */
    public Item(String description, String name, int Weight, boolean moveable) 
    {
        this.description = description;
        this.name = name;
        this.weight = weight;
        this.moveable = moveable;       
    }

    /**
     * Return the description of the item (the one that was defined
     * in the constructor).
     */
    public String getDescription()
    {
        return description;
    }
    
    /**
     * Return the name of the item (the one that was defined
     * in the constructor).
     */
    public String getName()
    {
        return name;
    }
    
    public boolean isMoveable()
    {
        return (moveable == false);
    }
    
    /**
     * Return the weight of the item 
     */
    public int getWeight()
    {
        return weight;
    }
    
}
Answer  
There is no answer at this time.

Comments  
Subject: Re: Java toString() and no value return problem
From: actinoid-ga on 06 Apr 2005 05:04 PDT
 
hello,

Firstly Item@f9c40 is printing the memory address of your item as it
has no tostring defined for the class. this is normal java behaviour.

If you want to print out a description of your Item class object like
this System.out.println(theItems); you need to define the method
toString() in the Item class. Every object in java can have a toString
method which is defined in its class.

So in the Item class add something like this.

e.g. public String stString()
     {
         String theName = "Item name : "+this.name+"\n";
         String theDescription = "Item description : "+this.description+"\n";
         String theWeight = "Item Weight : "+this.weight+"\n";
         String isMoveable = "Item movable : "+this.moveable+"\n";
         return "Item toString :
\n"+theName+theDescription+theWeight+isMovable+"\n";
     {
Subject: Re: Java toString() and no value return problem
From: nihplod-ga on 06 Apr 2005 13:31 PDT
 
He means...

public String toString( )
{
  return.....

}

You can do this in all your objects, so that way, when you print them,
you can specify the output.
Subject: Re: Java toString() and no value return problem
From: nihplod-ga on 06 Apr 2005 13:33 PDT
 
Also, when returning things like in your getName() method, you might
find it easier (and more "correct"?) to use:

return this.name;

to explicity state that "name" is an attribute of the current object, "this".
Subject: Re: Java toString() and no value return problem
From: drunkpanda-ga on 06 Apr 2005 15:04 PDT
 
hi actinoid and nihplod i have done something like this and it really
solve my problem thank you for spending time to help me, Drunkpanda

// in Player class 
public String getName()
    {
        return this.name;
    }
    
public String toString()
    {
        return this.description+this.name+this.weight+this.moveable;
    }

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy