做了几道个二维数组的题目与简单的二维数组题目
对二维数组的更深理解,对tic-tac-toe的编写:
首先要列出矩阵:
final int SIZE = 3; //读入矩阵
int[][] broad = new int[SIZE][SIZE];
boolean gotResult = false;
int numOfX = 0;
int numOfO = 0;
for(int i = 0;i<SIZE;i++)
{
for(int j = 0;j<SIZE;j++)
{
broad[i][j] = in.nextInt();
}
}
再检查行,检查列:
for(int i = 0;i < SIZE; i++) //检查行
{
numOfX = 0;
numOfO = 0;
for(int j = 0;i < SIZE;i++)
{
if(broad[i][j]==1)
{
numOfX++;
}
else
{
numOfO++;
}
}
if(numOfX == SIZE || numOfO == SIZE);
{
gotResult = true;
break;
}
if(!gotResult) //检查列
{
for(int i = 0;i < SIZE; i++)
{
numOfX = 0;
numOfO = 0;
for(int j = 0;i < SIZE;i++)
{
if(broad[j][i]==1)
{
numOfX++;
}
else
{
numOfO++;
}
}
if(numOfX == SIZE || numOfO == SIZE);
{
gotResult = true;
break;
}
}
再对对角线进行检查:
if(!gotResult) //主对角线
{
numOfX = 0;
numOfO = 0;
for(int i = 0;i < SIZE; i++)
{
if(broad[j][i]==1)
{
numOfX++;
}
else
{
numOfO++;
}
}
if(numOfX == SIZE || numOfO == SIZE);
{
gotResult = true;
}
}
if(!gotResult) //次对角线
{
numOfX = 0;
numOfO = 0;
for(int i = 0;i < SIZE; i++)
{
if(broad[i][SIZE-i-1]==1)
{
numOfX++;
}
else
{
numOfO++;
}
}
if(numOfX == SIZE || numOfO == SIZE);
{
gotResult = true;
}
}
输出结果:
if(gotResult)
{
if(numOfX == SIZE)
{
System.out.println("X WIN");
}
else
{
System.out.println("O WIN");
}
}