2012-10-27 54 views
-2

我手边有一些微不足道的问题。所以我试图阻止我的计数器c增加for循环。只有在空的时候,我才会在池塘里填满一个点。如果它已经装满了另一条鱼(白色或红色),我不希望柜台增加。一旦池塘中的一个点(或元素)被填满,它就不能再被填满。所以最终应该有500只白色鱼和5只红色鱼。防止递增

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

我正确使用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? 
     } 
    } 
} 
+0

您似乎有点不喜欢以这种方式通过循环增加值。你能解释一下你想要完成什么吗? – Makoto

回答

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; 
} 
+0

非常感谢你!这正是我正在寻找的:) – Sozziko

+0

@Sozziko:很高兴我能帮上忙。只要记住,不要仅仅因为它上次工作而编写代码,要先计划你想要做的事情,然后写出代码。你的问题是关于“防止递增”,但你实际上并不需要有一个计数器。祝你好运! – durron597

1
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循环没有意义的。

+0

对不起,我实际上是从内存中写出代码,因为我目前没有我的笔记本电脑。所以我正在手工完成我的任务,然后将它复制到日食中。 – Sozziko

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? 
    } 
}