首页 > 解决方案 > 在 if 语句中迭代数组

问题描述

我正在用可定制的规则构建生活游戏。我从一个函数接收一个数字数组,我需要遍历该数组以获取一组数字。我需要在不知道数组长度的情况下将这些数字添加到 if 语句中,以更新生活游戏的规则。以下是代码示例:

if(nAlive < 2)
  next[i][j] = false;
else if(nAlive == 2 || nAlive == 3)
  next[i][j] = true;
else
  next[i][j] = false;

我需要的是(这是伪代码):

if(nAlive == surviving[0] || nAlive == surviving[1] || ... nAlive == surviving[n])
  next[i][j] = true;
else
  next[i][j] = false;

标签: javaarrays

解决方案


答案是:

if(alive[i][j])
                {
                    next[i][j] = false;
                    for (int x = 0; x < surviving.length; x++) {
                        if (surviving[x] == nAlive)
                            next[i][j] = true;
                    }
                }

推荐阅读