题解 | #井字棋#
井字棋
http://www.nowcoder.com/practice/0375c1d206ef48a3894f72aa07b2fdde
解题思路
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sin = new Scanner(System.in);
String[] c = new String[9];
int ic = 0;
while(sin.hasNext()){
c[ic++] = sin.next();
}
// 把一维数组变成二维数组
String[][] cc = new String[3][3];
int con = 0;
for(int n = 0;n<3;n++){
for(int m=0;m<3;m++){
cc[n][m] = c[con++];
}
}
// 玩 “井”字棋
String s = print1(cc);
String s2 = print2(cc);
String s3 = print3(cc);
if(s.equals("K") || s2.equals("K") || s3.equals("K")){
System.out.println("KiKi wins!");
}else if(s.equals("B") || s2.equals("B") || s3.equals("B")){
System.out.println("BoBo wins!");
}else {
System.out.println("No winner!");
}
}
public static String print1(String[][] list){
String s = "";
for(int n = 0;n<3;n++){
for(int m=0;m<3;m++){
s += list[n][m];
}
if(s.equals("KKK")){
return "K";
}else if(s.equals("BBB")){
return "B";
}
//清空字符串
s = "";
}
return "O";
}
public static String print2(String[][] list){
String s = "";
int i = 0;
for(int n = 0;n<3;n++){
for(int m=0;m<3;m++){
s += list[m][i];
}
i++;
if(s.equals("KKK")){
return "K";
}else if(s.equals("BBB")){
return "B";
}
//清空字符串
s = "";
}
return "O";
}
public static String print3(String[][] list){
String s = "";
for(int n = 0;n<1;n++){
for(int m=0;m<3;m++){
s += list[m][m];
}
if(s.equals("KKK")){
return "K";
}else if(s.equals("BBB")){
return "B";
}
//清空字符串
s = "";
}
int t = 2;
for(int n = 0;n<1;n++){
for(int m=0;m < 3;m++){
s += list[m][t--];
}
if(s.equals("KKK")){
return "K";
}else if(s.equals("BBB")){
return "B";
}
//清空字符串
s = "";
}
return "O";
}
}