【问题标题】:Returning to the start of a while loop mid-loop?返回到循环中间循环的开始?
【发布时间】:2014-12-08 17:27:57
【问题描述】:

我正在做本学期的最后一次评估,有趣的是,我编写的代码似乎没有错误,除了我刚刚解决的一些简单错误。但是,我遇到了最后一个错误,我无法理解。

我正在做的程序是一个随机数生成器,使用 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++;
    }
}

}

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

【问题讨论】:

    标签: arrays loops while-loop continue


    【解决方案1】:

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

    while (i < random50.length);
    

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

    一旦这个问题得到解决,您对continue; 的使用应该会按预期工作。

    编辑:

    下面还有同样的问题:

    if (found);
    

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

    【讨论】:

    • continue 不再是错误,现在当我将值存储到数组中时出现编译错误,即 random50[i] = n;值不可达
    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 2018-08-22
    • 2011-08-09
    • 1970-01-01
    • 2021-12-18
    • 2015-12-13
    • 2020-09-05
    • 2011-04-04
    相关资源
    最近更新 更多