java 如何从循环中返回一个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10526576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:25:33  来源:igfitidea点击:

How to return a value from loop?

javafor-loop

提问by Babu R

Hi I am using a method which have to returns the subsequent values from the loop. But the return statement works outside the loop only. How can I return the value within the loop?

嗨,我正在使用一种必须从循环中返回后续值的方法。但是 return 语句只在循环之外工作。如何在循环中返回值?

Here is the code:

这是代码:

for (int i = 0; i < list.size (); i++)
{
    Iterator <String> it1 = //getting some list values
    double min = Double.parseDouble (it1.next ());
    double temp1 = 0;
    while (it1.hasNext ()) {
        if (it != null)
        {
            temp1 = Double.parseDouble (it1.next ()); 
        }                                   
        if (temp1 < min)
            min = temp1;
    } 
}
return min;

I want to return min value within the loop. How is it possible? Please help me.. Thanks in advance..

我想在循环中返回最小值。这怎么可能?请帮助我.. 提前致谢..

回答by FThompson

It's done in the same way as returning outside of a loop, except that you need to ensure that your method will return a value under all circumstances (excluding uncaught exceptions, etc). The following is your code with a return within the for loop.

它的完成方式与在循环外返回的方式相同,只是您需要确保您的方法在所有情况下都将返回一个值(不包括未捕获的异常等)。以下是在 for 循环中返回的代码。

for(int i=0;i<list.size();i++)
{
    Iterator<String> it1 = //getting some list values
    double min = Double.parseDouble(it1.next());
    double temp1=0;
    while(it1.hasNext()){
        if(it!=null)
        {
            temp1 = Double.parseDouble(it1.next()); 
        }                                   
        if(temp1 < min)
             min = temp1;
    }
    return min; 
}
return 0;

Although that most likely doesn't implement your function correctly, it shows that returning within a loop is possible. It also removes the need for a for loop altogether, but as I said before, that code is simply an example that shows returning within a loop is possible.

尽管这很可能没有正确实现您的函数,但它表明在循环内返回是可能的。它还完全不需要 for 循环,但正如我之前所说,该代码只是一个示例,表明可以在循环内返回。

回答by Hot Licks

A) You canreturnfrom a loop.

A)你可以return从一个循环。

B) The more "structured" approach is to set a variable to some bogus/default value ahead of the loop, then set it to the valid value within the loop before executing a break. Return the value on exit from the loop.

B)更“结构化”的方法是在循环之前将变量设置为某个虚假/默认值,然后在执行break. 在退出循环时返回值。