我已经有一个java程序可以正常工作。我尝试在php中编写相同的文件并遇到一些错误。 例如,在此代码中
for ($i=0; $i<64; $i++) {
$r=$i/8;
$c=$i%8;
$temp=1;
for ($j=-1; $j<=1; $j+=2) {
for ($k=-1; $k<=1; $k+=2) {
while(" " == $chessBoard[$r+$temp*$j][$c+$temp*$k])
{
//some other code here
}
}
}
}
$ chessBoard是一个二维数组
$chessBoard= array
(
array("r","k","b","q","a","b","k","r"),
array("p","p","p","p","p","p","p","p"),
array("0","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
array("P","P","P","P","P","P","P","P"),
array("R","K","B","Q","A","B","K","R")
);
我知道当我试图访问$ chessBoard [$ r + $ temp * $ j] [$ c + $ temp * $ k]时会发生错误,例如$ r为0且$ j为-1,然后我得到0 + 1 * -1这是-1,但我不知道如何摆脱这个问题,仍然让程序正常工作。我仍然不清楚为什么我在java中没有相同的问题。
答案 0 :(得分:0)
在代码之前
while(" " == $chessBoard[$r+$temp*$j][$c+$temp*$k])
{
//some other code here
}
投入:
if($r+$temp*$j < 0 || $c+$temp*$k) continue;
这将转到for循环的下一次迭代,不会遇到任何indexoutofboundsexception