考试当时未通过,这是我后来写的代码,有错误请指出
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static final char X = 'X';
public static final char O = 'O';
public static int check(char[][] a) {
int xflag = 0;
int oflag = 0;
// -
for (int i = 0; i < 3; i++) {
if (a[i][0] != '.' && a[i][0] == a[i][1] && a[i][0] == a[i][2]) {
if (a[i][0] == X)
xflag = 1;
else
oflag = 1;
}
}
// |
for (int i = 0; i < 3; i++) {
if (a[0][i] != '.' && a[0][i] == a[1][i] && a[0][i] == a[2][i]) {
if (a[0][i] == X)
xflag = 1;
else
oflag = 1;
}
}
// \
if (a[0][0] != '.' && a[0][0] == a[1][1] && a[0][0] == a[2][2]) {
if (a[0][0] == X)
xflag = 1;
else
oflag = 1;
}
// /
if (a[0][2] != '.' && a[0][2] == a[1][1] && a[0][0] == a[2][0]) {
if (a[0][2] == X)
xflag = 1;
else
oflag = 1;
}
if (xflag == 1 && oflag == 0) {
return 1;
} else if (xflag == 0 && oflag == 1) {
return 2;
} else if (xflag == 1 && oflag == 1){
return 3;
} else {
return 0;
}
}
public static Map<String, Object> count(char a[][]) {
Map<String, Object> res = new HashMap<String, Object>();
Integer x = 0;
Integer o = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == X) {
x++;
} else if (a[i][j] == O) {
o++;
}
}
}
res.put("x", x);
res.put("o", o);
return res;
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
char a[][] = new char[3][3];
for (int i = 0; i < 3; i++) {
String s = cin.next();
a[i][0] = s.charAt(0);
a[i][1] = s.charAt(1);
a[i][2] = s.charAt(2);
}
Map<String, Object> res = count(a);
Integer x = (Integer) res.get("x");
Integer o = (Integer) res.get("o");
Integer winner = check(a);
if (winner == 1) {
// 先手获胜或者不合法
if (x - o == 1 && x + o <= 9) {
System.out.println("1 won");
} else {
System.out.println("x");
}
} else if (winner == 2) {
// 后手获胜或者不合法
if (x - o == 0 && x + o <= 9) {
System.out.println("2 won");
} else {
System.out.println("x");
}
} else if(winner==3) {
System.out.println("x");
} else {
// 无获胜
if (x + o == 9 && x == 5 && o == 4) {// 平局
System.out.println("Draw");
} else if (x + o < 9 && x - o == 1) {// 先手
System.out.println(1);
} else if (x + o < 9 && x == o) {// 后手
System.out.println(2);
} else {
System.out.println("x");
}
}
}
}
}