-2

我手头有一个小问题。所以我试图阻止我的计数器 c 增加 for 循环。我只是在池塘空的时候才试图填补池塘中的一个地方。如果它已经装满了另一条鱼(白色或红色),我不希望计数器增加。一旦池塘中的一个点(或者更确切地说是元素)被填满,就不能再次被填满。所以到最后应该有 500 条白鱼和 5 条红鱼。

我觉得好像我使用了错误的条件语句来解决这个问题。一旦我的计数器增加,调用方法 placeFish 的 while 语句也会增加白色或红色计数器,这不是我想要做的。我不断得到不是 500 也不是 5 的白色/红色鱼的总量,而是更低,因为当理想情况下我不希望它们增加时,while 计数器正在增加。

我使用 for 语句是否正确?我试过一段时间,但它似乎也没有工作。

public static void fishes (int[][] pond) {
            //pond has dimensions [50][50] in a different method that call fishes
            //every element in the 2D array pond is already set to value 0
    int whitefish = 500;
    int redfish= 5;
    int whitefishvalue = 1
    int redfishvalue = 2
    int white = 0;
    int red = 0;
    while (white < whitefish)
    {
        placeFish (pond, whitefishvalue);
        white++;
    }
    while (red < redfish) 
    {
        placeFish (pond redfishvalue);
        redd++;
    }
}

public static void placeFish(int[][] pond, int newFish) {
    int a = random.nextInt(pond.length);
    int b = random.nextInt(pond[0].length);
            int spot = 0;

    for (int c = 0; c < 1; c++)
    {
        if (pond [a][b] == spot)
        {
            pond[a][b] = newFish;
            c++;
                    //How to stop c++ from incrementing?
        }
    }
}
4

3 回答 3

2

我不确定您要做什么,但是我认为这就是您想要的...这将在数组中随机搜索以寻找一个位置,当您找到一个位置时它将停止,然后将鱼放置那里。

public static void placeFish(int[][] pond, int newFish) {
    int spot = 0;
    int a;
    int b;

    do
    {
        a = random.nextInt(pond.length);
        b = random.nextInt(pond[0].length);
    } while (pond [a][b] != spot);

    pond[a][b] = newFish;
}
于 2012-10-27T02:17:26.073 回答
2
for (int c = 0; c < 1; c++) {
    if (pond [a][b] == spot) {
        pond[a][b] = newFish;
        c++; //How to stop c++ from incrementing?
    }
}

你实际上c在这个循环中增加了两次,我猜这不是你想要做的。第一个位置在第一行。记住一个for循环,一般写成

for (initialize; condition; increment) {
    // stuff goes here
}

就相当于while循环

initialize;
while (condition) {
    // stuff goes here
    increment;
}

因此,在循环的每次迭代结束时,它会自动递增c.

您增加的另一个地方c是在if语句的正文中。这只发生在pond[a][b] == spot. 因此,在确实如此的迭代中,您c总共增加两次,一次在此if语句中,一次在循环结束时。

我猜你只想在什么时候增加一次,pond[a][b] == spot否则根本不增加,对吧?如果是这样,这很容易解决:只需删除在每次循环迭代结束时运行的递增语句。

for (int c = 0; c < 1;) {
    // stuff goes here
}

if这样,您在语句中只剩下一个增量行。


顺便说一句,请注意,使用for只有一次迭代的循环是没有意义的。

于 2012-10-27T02:20:43.280 回答
0

你的措辞很混乱,但我假设你不希望你的 for 循环每次都增加?

for (int c = 0; c < 1;) //It's not necessary to put an increment there.  You can in fact write a loop like for(;;) and escaping it via break
{
    if (pond [a][b] == spot)
    {
        pond[a][b] = newFish;
        c++;
                //How to stop c++ from incrementing?
    }
}
于 2012-10-27T02:21:49.197 回答