1

I am trying to display the output as "1(10) 2(23) 3(29)" but instead getting output as "1 2 3 (10)(23)(29)". I would be grateful if someone could have a look the code and possible help me. I don't want to use arraylist.

the code this

// int[] Groups = {10, 23, 29}; in the constructor

public String toString()
{
    String tempStringB = "";
    String tempStringA = " ";
    String tempStringC = " ";

    for (int x = 1; x<=3; x+=1)
    {
       tempStringB = tempStringB + x + " ";
    }

    for(int i = 0; i < Group.length;i++)
    {
        tempStringA = tempStringA + "(" + Groups[i] + ")";
    }
    tempStringC = tempStringB + tempStringA;

    return tempStringC;
} 

2 Answers 2

2

The problem is that you are appending all of the indices to one String and all of the elements to another, and then concatenating the two.

Instead, try building one String (and remember to use StringBuffer/StringBuilder, since it is more efficient than String concatenation):

public String toString() {
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < Groups.length; i++) {
    sb.append(i+1).append('(').append(Groups[i]).append(')');
  }
  return sb.toString();
}
Sign up to request clarification or add additional context in comments.

4 Comments

This outputs "0(10) 1(23) 2(29)".
Ah, he wants 1-based. Fixed.
could I place the index in component 1 then 2 and 3 instead 0, 1, 2. At the moment even thought a tempString has been created to place arrays it doesn't actually presents the components. Currently the index 10, 23 abd 29 is placed in component starting from 0. Is it possible to place index 10 in component 1, index 23 in component 2 and index 29 in index 3. Show output "1(10) 2(23) 3(29)"
Yes, you can do that. Just allocate your array to be one space larger than necessary, since an array whose highest index is 3 must be of size 4.
0

You should use :

// int[] Groups = {10, 23, 29}; in the constructor

public String toString()
{
    String tempStringB = "";

    for(int i = 0; i < Group.length;i++)
    {
       tempStringB = (i==0?"":" ")+ tempStringB + (i+1) + " "+ "(" + Groups[i] + ")";
    }
    return tempStringB;
} 

But by the way using a StringBuffer would be clever especially if your Group become bigger

1 Comment

StringBuilder is the preferred choice nowadays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.