コンピュータとユーザーの間でTic-Tac-Toeのゲームのコードを記述しています。移動を行うために、ボード上で占有されていないスポットのリストがパラメータとして提供され、ユーザにとっては、入力がリスト内にあるかどうかを比較するのに本当に有用です。そうであれば、それは合法的な動きになります。配列のJava ArrayListには予期しない結果が返される
ここに私のコードです。それは新しい動きがリストに含まれていないと私はなぜ知りませんと言い続ける。私はここでデータベースを検索して同様の問題を発見したが、いくつかの関連性があるが決定的なものは見つからなかった。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class UserTTTPlayer implements TicTacToePlayer{
@Override
public int[] makeMove(ArrayList<int []> unusedMoves) {
Scanner in = new Scanner (System.in);
System.out.println("Your move, user?");
String input = in.nextLine();
int [] move = checkInput(input, unusedMoves);
while (move == null){
input = in.nextLine();
move = checkInput(input, unusedMoves);
}
return move;
}
private int [] checkInput(String input, ArrayList<int []> unusedMoves){
System.out.println("Unused moves: ");
for (int [] move: unusedMoves)
System.out.println(Arrays.toString(move));
//error checking for the length of the input
if (input.length() < 1 || input.length() > 2){
System.out.println("Invalid input. Please try again.");
return null;
}
else{
//convert the input from string to int
int col = input.charAt(0) - 'a';
int row = input.charAt(1) - '0';
int [] move = {row, col};
System.out.println("Intended move: " + Arrays.toString(move));
System.out.println(unusedMoves.contains(move));
//error checking for the bounds of the board
if (col > 3 || col < 0 || row > 3 || col < 0){
System.out.println("Invalid input.");
return null;
}
//error checking for if the space is available
else if (!unusedMoves.contains(move)){
System.out.println("That space is already occupied.");
return null;
}
return move;
}
}
}
これはその出力です。ボードや他の印刷は別のクラスからのものですが、問題とは関係ないと思います。私はそれが新しい動きを持っていると言うリストを出力しますが、まだfalseを返します。
You go first. You will be X's.
a b c
0 - - -
1 - - -
2 - - -
Your move, user?
a0
Unused moves:
[0, 0]
[0, 1]
[0, 2]
[1, 0]
[1, 1]
[1, 2]
[2, 0]
[2, 1]
[2, 2]
Intended move: [0, 0]
false
That space is already occupied.
助けてください。
配列にはequalsメソッドが実装されていません。これはcontainsメソッドのリストで使用されています – Rustam
'col 'を3回比較します:' col> 3 || col < 0 || row > 3 || col <0 'である。ちょうどそれを見つけた。 – rbento
[this](http://stackoverflow.com/questions/4849051/using-contains-on-an-arraylist-with-integer-arrays)の可能な複製。それはまったく役に立ちますか? – Hill