简体   繁体   中英

“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]+" - ");
}   

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.

If this is C#, you could use:

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

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM