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
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();
}
-
This outputs "0(10) 1(23) 2(29)".Péter Török– Péter Török2010年06月11日 16:39:02 +00:00Commented Jun 11, 2010 at 16:39
-
Ah, he wants 1-based. Fixed.danben– danben2010年06月11日 16:55:14 +00:00Commented 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)"DiscoDude– DiscoDude2010年06月11日 21:25:42 +00:00Commented 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.danben– danben2010年06月11日 23:39:36 +00:00Commented Jun 11, 2010 at 23:39
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
-
3StringBuilder is the preferred choice nowadays.Brett Kail– Brett Kail2010年06月11日 16:17:38 +00:00Commented Jun 11, 2010 at 16:17