Results 1 to 3 of 3
  1. #1
    01allenh is offline Member
    Join Date
    Mar 2009
    Posts
    2
    Rep Power
    0

    Default toString() method

    I'm overriding the toString() method for a Polygon class. An instance of Polygon has n points (i.e the number of points varies). These points are stored in an array of points, how do I convert these points to a string representation when the number of points is different for each instance of the Class? Is there some way of recursively doing this?

  2. #2
    MasterD is offline Member
    Join Date
    Mar 2009
    Location
    Germany
    Posts
    22
    Rep Power
    0

    Default

    You could try it like that
    Java Code:
    Point[] points;
    ...
    // Returns "2:(1,2):(2,3)", if your point's toString methode returns "(x,y)"
    public String toString() {
    String s = points.length;
    for(Point p : points) {
    s += ":" + p.toString();
    }
    return points;
    }
    even
    Java Code:
    public String toString() {
      return points.toString();
    }
    is possible.

    I wouldn't go for any recursion.

  3. #3
    arseny is offline Member
    Join Date
    Mar 2009
    Posts
    25
    Rep Power
    0

    Default

    You can also use a StringBuffer class - you will be able to pass it inside method call to fill it inside method. Concatenation of two strings (the '+' operator) always give a new String instance - using StringBuffer you can use a single instance.

Similar Threads

  1. toString question
    By mayhewj7 in forum New To Java
    Replies: 1
    Last Post: 01-29-2009, 07:41 PM
  2. question about writing a toString method
    By heather.diggs in forum New To Java
    Replies: 2
    Last Post: 11-12-2008, 11:13 PM
  3. toString() method of java.security.MessageDigest
    By Nicholas Jordan in forum Advanced Java
    Replies: 4
    Last Post: 09-18-2008, 02:32 PM
  4. toString method
    By apfroggy0408 in forum New To Java
    Replies: 6
    Last Post: 01-31-2008, 04:08 AM
  5. Can i just use toString?
    By cachi in forum New To Java
    Replies: 1
    Last Post: 07-31-2007, 08:32 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
  •