我相信您需要看的是第一批代码。其余的代码是在万一我缺少某些东西的情况下。
编辑:确实将第二个j更改为k可解决此问题。我循环了两次j,对于我的数组,值变得太大了。谢谢!
public static void makeMove(){
char[] path = new char[TicTacToeArray.length];
int[][] DefensiveOppsArray = new int[TicTacToeArray.length][TicTacToeArray.length];
for(int i=0; i < DefensiveOppsArray.length; i++){
for(int j=0; j < DefensiveOppsArray.length; j++){
DefensiveOppsArray[i][j] = 0;
}
}
for(int i=0; i < DefensiveOppsArray.length; i++){
for(int j=0; j < DefensiveOppsArray.length; j++){
//path for straight down
for(j=0; j < DefensiveOppsArray.length; j++){
path[j] = TicTacToeArray[i][j];}
DefensiveOppsArray[i][j]=DefensiveOppsArray[i][j] + 1;
}
}
}
我一直在为井字游戏Java游戏进行这项工作,但一直卡在“线程“主”中的异常” java.lang.ArrayIndexOutofBoundsException:3.此错误来自行
DefensiveOppsArray[i][j]=DefensiveOppsArray[i][j] + 1;
。这必须表示我不知何故未正确定义DefensiveOppsArray的大小,我在做什么错?TicTacToeArray继承自UserTicTacToe。测试课程很简单
public class Test3{
public static void main(String[] args){
IntelligentTicTacToe2.promptUserTTT();
}
}
我需要创建一个与TicTacToeArray长度相同的DefenceOppsArray,以便可以操纵数字,从而确定最佳移动方式。不幸的是,我在简单地在DefenceOppsArray中创建和处理数字的过程很费劲。
public class IntelligentTicTacToe2 extends UserTicTacToe{
public static void promptUserTTT(){
//read the input size
System.out.print("Enter TicTacToe Array Size: ");
int size = UserInput.readInt();
System.out.println("");
//start the game
UserTicTacToe.startTTT(size);
//keep track of consecutive errors
int consecutiveErrors = 0;
//display the initial game board
UserTicTacToe.displayTTT();
//let the user keep playing forever if they want to
while(true){
//get the input symbol from the user
System.out.print("Enter Symbol (X or O): ");
String symbol = UserInput.readString();
System.out.println("");
//hopefully the string is just one character - if not get just
//the first character
char sym = '*';
if(symbol.length() > 0){
sym = symbol.charAt(0);
}
//if the symbol was a Q, then quit
if(sym == 'Q'){
break ;
}
//get the row and column
System.out.print("Enter Row to Place Symbol: ");
int row = UserInput.readInt();
System.out.println("");
System.out.print("Enter Col to Place Symbol: ");
int col = UserInput.readInt();
System.out.println("");
//update the game board and see if input was valid
boolean inputValid = UserTicTacToe.updateTTT(sym,row,col);
//re-display the game board if input was accepted
if(inputValid){
UserTicTacToe.scoreTTT();
UserTicTacToe.displayTTT();
consecutiveErrors = 0;
}
//if input was rejected, print a message, increment error count,
//and quit if we are on the 5th error
else{
System.out.println("Invalid Input!");
if(consecutiveErrors >= 4){
break ;
}
consecutiveErrors++;
}
makeMove();
}
}
最佳答案
问题是您在嵌套循环中两次使用j
作为计数器
这是出问题的地方:
for(int i=0; i < DefensiveOppsArray.length; i++){
for(int j=0; j < DefensiveOppsArray.length; j++){
//path for straight down
for(j=0; j < DefensiveOppsArray.length; j++){ // << here you use j again as counter
path[j] = TicTacToeArray[i][j];
DefensiveOppsArray[i][j]=DefensiveOppsArray[i][j] + 1;
}
}
}
也许您编码了一个循环太多?