初学者,跟着翁恺在慕课上到了第五课的二维数组
试着写了下实现井字棋判断胜利的代码
输入的1,2,0分别对应着玩家1,玩家2,空白处
自己debug感觉结果是对的
想请各位大老们帮忙看一下,有没有错误或者可以优化的地方。。谢谢!
```java
package class_paper;
import java.util.Scanner;
public class Tic_Tac_Toe {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
final int SIZE = 3;
int[][] tic = new int[SIZE][SIZE];
boolean win = false;
//创建井字棋表
for ( int i = 0 ; i < tic.length ; i++)
{
for ( int j = 0 ; j < tic[i].length ; j++)
{
tic[i][j] = scan.nextInt();
while ( tic[i][j] < 0 || tic[i][j] >= 3)
{
System.out.println("请重新输入数字1或者2或者0:");
tic[i][j] = scan.nextInt();
}
System.out.println(tic[i][j]);
}
}
//检查行
for ( int i = 0 ; i < tic.length ; i++)
{
for ( int j = 0 ; j < tic[i].length ; j++)
{
win = true;
if ( tic[i][j] != tic[i][0] )
{
win = false;
break;
}
}
if ( win == true )
{
System.out.println("胜者为:" + tic[i][0]);
System.exit(0);
}
}
//检查列
for ( int j = 0 ; j < tic[0].length ; j++)
{
for ( int i = 0 ; i < tic.length ; i++)
{
win = true;
if ( tic[i][j] != tic[0][j])
{
win = false;
break;
}
}
if ( win == true)
{
System.out.println("胜者为:" + tic[0][j]);
System.exit(0);
}
}
//检查正对角线
win = true;
for ( int i = 0 ; i < tic.length ; i++)
{
if ( tic[i][i] != tic[0][0])
{
win = false;
break;
}
}
if ( win == true )
{
System.out.println("胜者为:" + tic[0][0]);
System.exit(0);
}
//检查反对角线
win = true;
for ( int i = SIZE - 1 ; i > 0 ; i--)
{
if ( tic[SIZE - 1 - i][i] != tic[0][i])
{
win = false;
break;
}
}
if ( win == true)
{
System.out.println("胜者为:" + tic[0][SIZE - 1]);
System.exit(0);
}
//没有胜者
System.out.println("很遗憾,本局游戏没有胜者!");
scan.close();
System.exit(0);
}
}