final int SIZE = 3;
// int[][] a = {
// {1,2,1},
// {1,2,2},
// {2,1,1}};
int[][] a = new int[SIZE][SIZE];
boolean gotResult = false;
int numofX = 0;
int numofO = 0;
boolean count=true;
for(int i=0;i<SIZE*SIZE;i++)
{
System.out.println("3X3規格:O/X輪流輸入座標:");
int x,y;
x = in.nextInt();
y = in.nextInt();
if(count)
{
a[x][y] = 1; //O贏
count=!count;
}
else
{
a[x][y] = 2; //X贏
count=!count;
}
//行
if(gotResult != true)
{
hang:
for(int q=0;q<a.length;q++)
{
numofO = 0;
numofX = 0;
for(int j=0;j<a.length;j++)
{
if(a[q][j] == 1)
{
numofO++;
}
else if(a[q][j] == 2)
{
numofX++;
}
}
if(numofX == SIZE || numofO == SIZE)
{
gotResult = true;
break hang;
}
}
}
//列
if(gotResult != true)
{
lie:
for(int q=0;q<a.length;q++)
{
numofO = 0;
numofX = 0;
for(int j=0;j<a.length;j++)
{
if(a[j][q] == 1)
{
numofO++;
}
else if(a[j][q] == 2)
{
numofX++;
}
}
if(numofX == SIZE || numofO == SIZE)
{
gotResult = true;
break lie;
}
}
}
//反對角線
if(gotResult != true)
{
numofO = 0;
numofX = 0;
for(int q=0,j=2;q<SIZE&&j>=0;q++,j--)
{
if(a[q][j] == 1)
{
numofO++;
}
else if(a[q][j] == 2)
{
numofX++;
}
}
if(numofX == SIZE || numofO == SIZE)
{
gotResult = true;
}
}
//對角線
if(gotResult != true)
{
numofO = 0;
numofX = 0;
for(int q=0;q<SIZE;q++)
{
if(a[q][q] == 1)
{
numofO++;
}
else if(a[q][q] == 2)
{
numofX++;
}
}
if(numofX == SIZE || numofO == SIZE)
{
gotResult = true;
}
}
if(gotResult)
{
if(numofO == SIZE)
{
System.out.print(" O 贏了!");
break;
}
else
{
System.out.print(" X 贏了!");
break;
}
}
else if(i == SIZE*SIZE)
{
System.out.print("平局");
break;
}
}
程序
程序的內容是雙方依次輸入九宮格的座標 (0,0)到(2,2)中的一個,每次輸入完後進行判斷,若某一方知足條件就結束輸入,並打印哪一方贏,若輸入結束後還沒得出勝負,則輸出平局。next
缺點:輸入過的座標,若是重複輸入的話,會佔用輸入次數,由於比較懶這個沒在開頭限制。co