#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Classes with Arrays and toString


    I have an assignment and I need to write a class with a method toString which converts ints and doubles and returns them all as strings. How can I return multiple values on multiple lines and how do I convert them to strings? This is all I have so far on this method:

    public String toString()
    {
    return guest;
    //must return all on multiple lines as strings w/ \n escaoe character
    }

    I also have to have an array in another class and I've never used them before. I'm supposed to create an array of objects from one class in the constructor for this class. Is this correct?

    public Hotel (String initialName)
    {
    name = initialName;
    Room[] theRooms = new Room[20];
    }

    If it is right, how do I use other instance variables if only one is initialized here? Instructions say only have a parameter for name in constructor.

    Thanks
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    how do I convert them to strings
    The String class has methods to convert several primitive types to Strings.

    Code:
    Room[] theRooms = new Room[20];
    That will create an array that can hold up to 20 Room objects.
    Have you tried to compile it yet to see if there are any errors?

    One problem I see is that the variable: theRooms is defined locally in a constructor and will disappear when the constructor execution exits. Define the variable at the class level if you want it to be around later.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2009
    Location
    London, ON
    Posts
    322
    Rep Power
    214
    Assuming the variable 'guest' is a primitive, you can "merge" it into a String if you will by simply adding it to the String. The following is enough to add a new line before the guest variable and return the result as a String.

    Code:
    return "\n"+guest;
    <Tetrad> the program I just wrote 1) compiled the first time without any errors and 2) worked like it was supposed to
    <Tetrad> I don't know whether to be proud or scared to death
    Originally Posted by DaWei_M
    That covers a multitude of your sins, right there.

IMN logo majestic logo threadwatch logo seochat tools logo