我在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();
}
正如您已经提到的,问题出在数据类型不匹配上。
解决此问题的最简单方法是使用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();
}
正如你所解释的语法是错误的,ArrayList没有任何像get(String(这样的方法。您需要维护计数,以便可以使用该计数获取它。所以你需要在这里改变你的逻辑。