我对synatx有一点问题。对于那里的所有问题:
selectButton = emptyButtons.get(field[i][0]);
或类似的任何我遇到错误
get(int) in List cannot be applied to get(Java.lang.string()).
解决此问题的正确语法是什么?
以下是代码:
private void computerMove() {
String[][] field = new String[3][3];
Random random = new Random(); //you may want to declare this as a class field
List<Button> emptyButtons = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
emptyButtons.add(buttons[i][j]);
}
}
}
Button selectButton;
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][2].equals("")){
selectButton = emptyButtons.get(field[i][2]);
}
else if (field[i][0].equals(field[i][2])
&& field[i][1].equals("")){
selectButton = emptyButtons.get(field[i][1]);
}
else if (field[i][1].equals(field[i][2])
&& field[i][0].equals("")){
selectButton = emptyButtons.get(field[i][0]);
}
else {
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
selectButton.setText("O");
selectButton.setTextColor(playerO);
turnsCount++;
isGameOver();
}
答案 0 :(得分:0)
正如您已经提到的,问题在于数据类型不匹配。
解决此问题的最简单方法是使用HashMap
而不是ArrayList
。
以下是使用HashMap
修改的代码:
private void computerMove() {
String[][] field = new String[3][3];
Random random = new Random(); //you may want to declare this as a class field
HashMap<Integer,Button> emptyButtons = new HashMap<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
emptyButtons.put(i*3 + j,buttons[i][j]);
}
}
}
Button selectButton;
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][2].equals("")){
selectButton = emptyButtons.get(i*3 +2);
}
else if (field[i][0].equals(field[i][2])
&& field[i][1].equals("")){
selectButton = emptyButtons.get(i*3 +1);
}
else if (field[i][1].equals(field[i][2])
&& field[i][0].equals("")){
selectButton = emptyButtons.get(i*3);
}
else {
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
selectButton.setText("O");
selectButton.setTextColor(playerO);
turnsCount++;
isGameOver();
}
答案 1 :(得分:-1)
正如您所解释的,语法错误,ArrayList没有像get(String)这样的方法。你需要保持计数,以便你可以使用那个数量。所以你需要在这里改变你的逻辑。