简体   繁体   English

“ return”语句与“ for loop”

[英]“return” statement with “for loop”

In java programming language, How can I implement "for loop" in return statement 在Java编程语言中,如何在return语句中实现“ for循环”

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.. 如果num数组有1000个项,并且我想返回所有这些元素,那么该如何像以前一样逐个写呢。

I tried by using for loop but give me an error 我尝试使用for循环,但给我一个错误

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. 如果在循环内部执行return ,则会中断循环。 What you want to do is to return a big string with all those other strings concat. 您要做的是返回一个带有所有其他字符串concat的大字符串。 Do a 做一个

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

where s is a cache string. 其中s是缓存字符串。 Then, after the loop, do a return s; 然后,在循环之后,执行return s; so you have them all. 所以你们都拥有。

If this is C#, you could use: 如果这是C#,则可以使用:

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

If this is Java, you could use StringUtils.join : 如果是Java,则可以使用StringUtils.join

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

Section 14.1 Normal and Abrupt Completion of Statements of the standard says: 标准声明的第14.1节“ 正常和突然完成”说:

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. break(第14.15节),continue(第14.16节)和return(第14.17节)语句导致控制权转移,这可能会阻止包含它们的语句的正常完成。

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 . 只需在return之前将弦连接在一起。 You also don't need String.format . 您也不需要String.format Even better - if this is C# or Java, use a string builder. 甚至更好-如果是C#或Java,请使用字符串生成器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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