我正在创建一个Tic Tac Toe游戏(使用GUI),我正在使用2D数组来确定获胜者。我发现在用户点击电路板上的某个位置后,该阵列不会保存以前的值。
所以如果board [0] [0]为“X”,则数组为
[[X, 2, 3], [4, 5, 6], [7, 8, 9]]
之后如果用户点击[1] [1],则数组应为:
[[X, 2, 3], [4, X, 6], [7, 8, 9]]
但是它是:
[[1, 2, 3], [4, X, 6], [7, 8, 9]]
为什么会这样?
这是代码:
private class Play implements ActionListener{
public void actionPerformed(ActionEvent event){
JButton src = (JButton) event.getSource();
//create board
String[][] board = { {"1","2","3"},
{"4","5","6"},
{"7","8","9"}
};
// who's turn?
count++;
if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9 )
letter = playerChoice;
else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
letter = computerChoice;
//player choice - show button
if(src.equals(one)){
one.setText(letter);
one.setEnabled(false);
board[0][0]= letter;
}else if(src.equals(two)){
two.setText(letter);
two.setEnabled(false);
board[0][1] = letter;
}else if(src.equals(three)){
three.setText(letter);
three.setEnabled(false);
board[0][2] = letter;
}else if(src.equals(four)){
four.setText(letter);
four.setEnabled(false);
board[1][0] = letter;
}else if(src.equals(five)){
five.setText(letter);
five.setEnabled(false);
board[1][1] = letter;
}else if(src.equals(six)){
six.setText(letter);
six.setEnabled(false);
board[1][2] = letter;
}else if(src.equals(seven)){
seven.setText(letter);
seven.setEnabled(false);
board[2][0] = letter;
}else if(src.equals(eight)){
eight.setText(letter);
eight.setEnabled(false);
board[2][1] = letter;
}else if(src.equals(nine)){
nine.setText(letter);
nine.setEnabled(false);
board[2][2] = letter;
}
System.out.println(Arrays.deepToString(board));
答案 0 :(得分:1)
每次调用board
时,您正在创建一个新的本地变量actionPerformed
...
private class Play implements ActionListener {
public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();
//create board
String[][] board = {{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
};
//...
这意味着状态永远不会在呼叫之间保存,而是在每次呼叫时重新创建。
相反,board
应该是一个实例字段,例如......
private class Play implements ActionListener {
private String[][] board = {{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
};
public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();
count++;
if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9 )
letter = playerChoice;
else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
letter = computerChoice;
//...