回到while循环中间循环的开始?

时间:2014-12-08 17:27:57

标签: arrays loops while-loop continue

我正在为这个学期做最后的评估,有趣的是,我写的代码似乎没有错误,除了我刚刚解决的一些简单的错误。但是,我不知道最后一个错误,我无法理解。

我正在做的程序是一个随机数生成器,使用while循环生成数字并将它们存储在数组中,但是,必须使用第二个while循环来检查该数字是否已经在数组,如果该数字已经在数组中,则必须丢弃此数字,并且必须获取另一个值以放入相同的索引中。在此之后,阵列打印为5x 10的网格。但是,在第一个循环结束时使用continue命令时,它会出现错误:

Random50.java:52: error: continue outside of loop
continue;
^

尽管看起来很明显,但我不知道如何更改我的代码以使程序运行,我使用continue命令返回第一个循环的开头而不增加计数器变量,所以另一个值可以再次存储在同一个索引中。

import java.util.Random;
import java.util.Arrays;

public class Random50
{
   public static void main(String[] args)
   {
    // Declare and initalise array
    int[] random50 = new int[5];

    // Declare and initalise counter variable

    int i = 0;

    // Declare and initalise repeater variable

    int r = 0;

    // Generator while loop
    while (i < random50.length)
    {
        // Generate random number
        int n = (int) (Math.random() * 999) + 1;
        // Initalise variables for second while loop
        int searchValue = i;
        int position = 0;
        boolean found = false;

        // Duplicate while loop
        while (position < random50.length && !found)
        {
            if (random50[position] == searchValue)
            {
                found = true;
            }

            else
            {
                position++;
            }

        }

        // Return to first loop, determine if duplicate to return to the start of the loop early
        if (found);
        {
            continue;
        }

        // Store value into array
        random50[i] = n;

        // Print value and add to counter variable
        System.out.print(random50[i] + " ");
        r++;
        // reset counter variable to maintain grid
        if (r == 5)
        {
            System.out.println("");
            r = 0;
        }

        i++;
    }
}

}

那么,我怎样才能继续工作,换句话说,回到第一个循环中间循环的开始?

1 个答案:

答案 0 :(得分:1)

问题是你的while()循环由于过时;可能意外放置而立即终止:

while (i < random50.length);

所以你的整个循环体只会执行一次,无论条件如何(最有可能被优化掉)。

修复此问题后,您对continue;的使用应按预期工作。

修改

下面的问题相同:

if (found);

由于此行,您将始终在这些括号内执行continue;,因此以下代码无法访问。