import java.io.IOException;
import java.util.Random;
public class ComputerPlay {
public int Crow;
public int Ccol;
public void computerPlay() throws Exception{
try{
Random rand = new Random();
Crow = rand.nextInt(3)-1;
Ccol = rand.nextInt(3)-1;
} catch (ArrayIndexOutOfBoundsException e){
computerPlay();
}
//computerPlay();
if(ChessPad.board[Crow][Ccol] == ChessPad.EMPTY){
ChessPad.board[Crow][Ccol] = ChessPad.CROSS;
}
}
}
这段代码需要实现的是: Crow, Ccol是两个电脑随机输入的数字, 取值范围是1-3.判断, 如果board[Crow][Ccol]是empty(int 0), 则把Cross (int 2)赋给 board[Crow][Ccol]. 如果board[Crow][Ccol]的值不为empty, 则再从新随机输入数字, 找到一个空的board[][]并赋给2.
注:初始值都是empty(int 0);
用这段代码实现,如果当前随机输入值的board不为空,总是会throws exception “ArrayIndexOutOfBounds ” 。
改了好几遍,都不能避免 exception。
请问该如果修改啊?谢谢
------解决方案--------------------
需要注意的是:nextInt(3) 所返回的值,范围是 0~2