之前介绍的数组都是1维的,一个下标一个元素。
实际上可以是多维的
引入二维数组
int [][] a = new int [3] [5];
通常理解为a是3行5列的矩阵。
三维就3对[]
二维数组的遍历:
for ( int i = 0 ; i < 3; i++ )
{
for ( int j = 0; j < 5; j++ )
{
a[i][j] = i * j;
}
}
1.a[i][j]是一个int
2.表示第i行第j列上的单元
3.a[i,j]不存在
二维数组的初始化
<p class="p1"> <span class="s1">int</span> [] [] <span class="s2">a</span> = {</p><p class="p1"> <span> </span>{1,2,3,4},</p><p class="p1"> <span> </span>{1,2,3},</p><p class="p1"> };</p>
表示两行四列,最后一个自动补零
留意:
1.编译器会自己数数
2.每行一个{},逗号分开
3.最后的逗号可以存在,有这个传统
4.如果省略,表示补零
例子——tic-tac-toe游戏——井字过三关:
程序要输出是否有获胜方,是X还是O
自己整理老师的程序,未测试运行:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 表达大小的常量
final int SIZE = 3;
// 矩阵
int [][] board = new int [SIZE] [SIZE];
// 有无得到结果
boolean gotResult = false;
// 做4次判断——数数是否一行3个X或者O
int numOfX = 0;
int numOfO = 0;
int i ;
int j ;
// 读入矩阵——board.length,表示有几行
for ( i = 0; i < board.length ; i++)
{
// 某一行有几个——即表示有几列
for ( j = 0; j < board[i].length ; j++)
{
board [i][j] = in.nextInt();
}
}
// 检查行
if ( !gotResult )
{
numOfX = 0;
numOfO = 0;
for ( int i = 0; i < board.length ; i++)
{
for ( j = 0; j < board[i].length ; j++)
{
if ( board [i][j] = 1 )
{
numOfX ++;
}
else
{
numOfO ++;
}
}
if ( numOfX == SIZE || numOfO == SIZE )
{
gotResult = true;
}
}
}
// 检查列
if ( !gotResult )
{
numOfX = 0;
numOfO = 0;
for ( int j = 0; j < board.length ; j++)
{
if ( board [j][i] = 1 )
{
numOfX ++;
}
else
{
numOfO ++;
}
}
if ( numOfX == SIZE || numOfO == SIZE )
{
gotResult = true;
}
}
// 检测对角线
if ( !gotResult )
{
numOfX = 0;
numOfO = 0;
for ( j = 0; j < board.length ; j++)
{
if ( board [i] [i] == 1)
{
numOfX ++;
}
else
{
numOfO ++;
}
}
if ( numOfX == SIZE || numOfO == SIZE )
{
gotResult = true;
}
}
// 检测反对角线
if ( !gotResult )
{
numOfX = 0;
numOfO = 0;
for ( j = 0; j < board.length ; j++)
{
if ( board [i] [SIZE - i - 1 ] == 1)
{
numOfX ++;
}
else
{
numOfO ++;
}
}
if ( numOfX == SIZE || numOfO == SIZE )
{
gotResult = true;
}
}
if ( gotResult )
{
if ( numOfX == SIZE )
{
System.out.println("x赢了");
}
else
{
System.out.println("o赢了");
}
}
}
}
对角线和反对角线只要一层循环