这有点奇怪,但我的 java 代码不能正确比较字符。
我有这段代码循环遍历一个二维字符数组并将每个“I”替换为“D”
for (i = 0; i < 12; i++)
{
for (j = 0; j < 12; j++)
{
if (activeGrid[i][j] == 'I')
{
activeGrid[i][j] = 'D';
System.out.println("Changing [" + i + "][" + j + "]");
}
else
{
System.out.println("No I in [" + i + "][" + j + "]");
}
}
}
但是它似乎无法正常工作,这是一个示例运行:
0 1 2 3 4 5 6 7 8 9 A B
_ _ _ _ _ _ _ _ _ _ _ _
0 | | | | | | | | | | | | |
1 | | | | | | | | | | | | |
2 | | | | | | | | | | | | |
3 | | | | | | | | | | | | |
4 | | | | | | | | | | | | |
5 | | | | | |D| | | | | | |
6 | | | | | | | | | | | | |
7 | | | | | | | | | | | | |
8 | | | | | | | | | | | | |
9 | | | | | | | | | | | | |
10 | | | | | | | | | | | | |
11 | | | | | | | | | | | | |
0 1 2 3 4 5 6 7 8 9 A B
_ _ _ _ _ _ _ _ _ _ _ _
0 | | | | | | | | | | | | |
1 | | | | | | | | | | | | |
2 | | | | | | | | | | | | |
3 | | | | | | | | | | | | |
4 | | | | | |I| | | | | | |
5 | | | | |I|D|I| | | | | |
6 | | | | | |I| | | | | | |
7 | | | | | | | | | | | | |
8 | | | | | | | | | | | | |
9 | | | | | | | | | | | | |
10 | | | | | | | | | | | | |
11 | | | | | | | | | | | | |
(为了便于阅读,我删除了“No I in ...”部分)
然后它拒绝从这里更新,无论我尝试多少次,它都不会将 I's 更改为 D's。更令人困惑的是,有时它会改变我的部分或全部,然后稍后会卡住
我也看到与代码的其他部分类似的事情,一部分检查与 D 相邻的每个单元格并决定 D 是否应该传播,不传播的因素之一是单元格中是否已经存在 D 或 I,但是在某些单元格中,每次按 Enter 时,我都会看到值从 D 切换到 I,而且我还看到随机出现在 D 的海洋中
有任何想法吗?
[编辑]
活动网格的初始化如下:
public char[][] setActiveGrid (int x, int y)
{
char grid[][] = new char [12][12];
int Px;
int Py;
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++)
{
grid[i][j] = ' ';
}
}
grid[x][y] = 'D';
do
{
Px = (int) Math.ceil((Math.random() * 12) - 1);
Py = (int) Math.ceil((Math.random() * 12) - 1);
} while (Px == x && Py == y);
//grid[Px][Py] = 'P';
return grid;
}
它只会被这个改变:
public char[][] spreadDisease (char regionGrid[][], char activeGrid[][])
{
char regionFlag;
int i;
int j;
int xDiff;
int yDiff;
for (i = 0; i < 12; i++)
{
for (j = 0; j < 12; j++)
{
if (activeGrid[i][j] == 'D')
{
regionFlag = regionGrid[i][j];
for (xDiff = -1; xDiff < 2; xDiff = xDiff + 2)
{
if (regionGrid[(i+xDiff)][j] == regionFlag && (activeGrid[(i+xDiff)][j] != 'D' || activeGrid[(i+xDiff)][j] != 'I'))
{
activeGrid[(i+xDiff)][j] = 'X';
}
else
{
activeGrid[(i+xDiff)][j] = 'Y';
}
}
for (yDiff = -1; yDiff < 2; yDiff = yDiff + 2)
{
if (regionGrid[i][(j+yDiff)] == regionFlag && (activeGrid[i][(j+yDiff)] != 'D' || activeGrid[(i+xDiff)][j] != 'I'))
{
activeGrid[i][(j+yDiff)] = 'X';
}
else
{
activeGrid[i][(j+yDiff)] = 'Y';
}
}
}
}
}
return activeGrid;
}
regionGrid 是一个 2D 字符数组,其中填充了 + - * 和 ~ 的随机分类。D的传播规则是:
- 如果与 D 相邻的单元格具有与 D 相同的区域字符,则它们被设置为 D
- 否则,它们将设置为 I,然后在下一次运行时设置为 D。