开发者

Passing and Returning StringBuilders: Java

I was referred to this site by a friend. I like that I was able to look at some similar threads before I started this thread. Unfortunately, I didn't see anything about this specific issue.

I'm having an issue passing StringBuilders from object to object in Java. I don't know what the problem is and am lost. I can pass and return data all day. With StringBuilders, it just doesn't work. I'm thinking it's something really easy that i'm simply too frustrated to see.

I have a homework assignment which asks me to declare 3 Stringbuilders with my first name, middle name, and last name. No problem.

It also wants 3 objects to do different formats of the name. The formatting portion is easy. I can't figure out how to return the work back to the main.

Here's a snippet:

public class Builder
{
   public static void main(String[] args)
   {
      StringBuilder str1 = new StringBuilder("John");
      StringBuilder str2 = new StringBuilder("Que");
      StringBuilder str3 = new StringBuilder("Doe");

      ???  = entireName(str1, str2, str3);
   }

  public static String entireName(StringBuilder s1, StringBuilder s2, StringBuilder s3)
  {
        System.out.print(s1);
        //insert.s1('4', ' ');//format stuff, not really necessary (not a problem).
        Ststem.out.print(s2);
        //etc..
        System.out.print(s3);
开发者_开发知识库        return ????;
   }
}

the question marked stuff isn't filled in because nothing I put in there worked anyway. I've tried declaring separate strings to pass back. I've tried declaring the strings, then using those strings in the stringbuilder. I've got nothing. The formatting portion of this stuff is easy. If I can't return to the main, it's wrong.

I really appreciate any help. Thank you!


Assuming your prints are for debugging, you need s1.toString() and such

public static String entireName(StringBuilder s1, StringBuilder s2, StringBuilder s3)
  {
        System.out.print(s1.toString());
        //insert.s1('4', ' ');//format stuff, not necessary (not a problem)
        System.out.print(s2.toString());
        //etc..
        System.out.print(s3.toString());
        return s1.append(s2).append(s3).toString();
   }

I ran this, and it works:

public class Builder
{
   public static void main(String[] args)
   {
      StringBuilder str1 = new StringBuilder("John");
      StringBuilder str2 = new StringBuilder("Que");
      StringBuilder str3 = new StringBuilder("Doe");

      String s = entireName(str1, str2, str3);

      System.out.println(s);
   }

   public static String entireName(StringBuilder s1, StringBuilder s2,
            StringBuilder s3)
   {
        // debugging removed
        return s1.append(s2).append(s3).toString();
   }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜