0

我想保持简短。它返回后会发生什么true?它是否停止-循环for并返回do-while循环?我很困惑;请提供详细说明。

for (int i = 0; i < 6; i++) 
    {
        int pick;
        do 
        {
            pick = (int) Math.floor(Math.random() * 50 + 1);
        } 
        while (numberGone(pick, gui.numbers, i)); 
        gui.numbers[i].setText("" + pick);
    }
    boolean numberGone(int num, JTextField[] pastNums, int count) 
    { 
        for (int i = 0; i < count; i++) 
        {
            if (Integer.parseInt(pastNums[i].getText()) == num) 
            {
                return true;
            }
        }
        return false;
    }
4

2 回答 2

2

方法在遇到第一return条语句时立即返回控件。语句后面的任何代码return都不会被执行。所以在你的代码中:

boolean numberGone(int num, JTextField[] pastNums, int count) 
    { 
        for (int i = 0; i < count; i++) 
        {
            if (Integer.parseInt(pastNums[i].getText()) == num) 
            {
                // if this is executed, execution of this method will return from here
                return true;
            }
        }
        // this will be executed only when if statement is not executed and for loop finishes gracefully
        return false;
    }

注意:如果您不想在满足 if 条件时从方法返回并简单地结束循环,请使用break而不是return.

于 2013-08-15T00:36:35.487 回答
0

The function always exits when a return statement is encountered. No statement after that will be executed.
The only exception is try catch finally block.
finally block is always executed irrespective of whether return is encountered before it or not.

于 2013-08-15T00:38:43.403 回答