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;
} 
Daniel DiPaolo
56.5k14 gold badges119 silver badges116 bronze badges
asked Jun 11, 2010 at 16:09

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();
}
answered Jun 11, 2010 at 16:18
4
  • This outputs "0(10) 1(23) 2(29)". Commented Jun 11, 2010 at 16:39
  • Ah, he wants 1-based. Fixed. Commented Jun 11, 2010 at 16:55
  • 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)" Commented Jun 11, 2010 at 21:25
  • 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. Commented Jun 11, 2010 at 23:39
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

answered Jun 11, 2010 at 16:16
1
  • 3
    StringBuilder is the preferred choice nowadays. Commented Jun 11, 2010 at 16:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.