data
data

Reputation: 39

"return" statement with "for loop"

In java programming language, How can I implement "for loop" in return statement

I have this code

public String toString(){
return String.format(num[0]+" - "+num[1]+" - "+num[2]+" - "+num[3]+" - "+num[4]+" - "+num[5]+" - "+num[6]+" - "+num[7]+" - "+num[8]+" - "+num[9]+" - "+num[10]+" - "+num[11]+" - "+num[12]+"\n");
}

if num array have 1000 items , and I want to return all of these elements, how can I do that with out write it one by one like a previous one..

I tried by using for loop but give me an error

public String toString(){
for(int j=0 ; j<100 ; j++)
return String.format(num[j]+" - ");
}   

Upvotes: 0

Views: 26311

Answers (4)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36391

Section 14.1 Normal and Abrupt Completion of Statements of the standard says:

The break (§14.15), continue (§14.16), and return (§14.17) statements cause a transfer of control that may prevent normal completion of statements that contain them.

If you want to return several elements at once, then you may use a collection to aggregate the returned values.

Upvotes: 0

Forgotten Semicolon
Forgotten Semicolon

Reputation: 14100

If this is C#, you could use:

return String.Join(" - ", num);

If this is Java, you could use StringUtils.join:

return StringUtils.join(num, " - ");

Upvotes: 3

Lucas Famelli
Lucas Famelli

Reputation: 1615

If you do a return inside of a loop, it breaks the loop. What you want to do is to return a big string with all those other strings concat. Do a

public String toString(){
for(int j=0 ; j<100 ; j++)
s = s +" "+num[j];
}  

where s is a cache string. Then, after the loop, do a return s; so you have them all.

Upvotes: 4

Daniel A. White
Daniel A. White

Reputation: 190915

Just concat the strings together before the return. You also don't need String.format. Even better - if this is C# or Java, use a string builder.

Upvotes: 0

Related Questions