目录
用二维数组来表示一个棋盘:
创建一个原始的二维数组 11*11 0表示没有棋子 1表示黑子 2表示蓝子
int[][] chessArray = new int[11][11];
chessArray[1][2] = 1;
chessArray[2][3] = 2;
chessArray[6][6] = 2;
for (int[] i : chessArray) {
for (int e : i) {
System.out.print(e + "\t");
}
System.out.println();
}
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
将二维数组转换为稀疏数组
1.先遍历二维数组,得到非0数据的个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArray[i][j] != 0) {
sum++;
}
}
}
2.创建稀疏数组
int[][] sparseArray2 = new int[sum + 1][3];
sparseArray2[0][0] = 11;
sparseArray2[0][1] = 11;
sparseArray2[0][2] = sum;
int count = 0;//用来记录是第几个非 0 数据
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArray[i][j] != 0) {
count++;
sparseArray2[count][0] = i;
sparseArray2[count][1] = j;
sparseArray2[count][2] = chessArray[i][j];
}
}
}
3.输出稀疏数组
System.out.println();
System.out.println("得到的稀疏数组为:");
for (int[] i : sparseArray2) {
for (int d : i) {
System.out.print(d + "\t");
}
System.out.println();
}
得到的稀疏数组为:
11 11 3
1 2 1
2 3 2
6 6 2
利用io流实现与本地文件的交互
①.把稀疏数组存入本地文件中
FileWriter fw = null;
try {
File file = new File("array");
fw = new FileWriter(file);
for (int i = 0; i < sparseArray2.length; i++) {
for (int j = 0; j < 3; j++) {
fw.write(sparseArray2[i][j] + " ");
}
fw.write("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
②.把二维数组从本地文件中取出来
int[][] ints = null;
BufferedReader br = null;
try {
FileReader fr = new FileReader("array");
br = new BufferedReader(fr);
ArrayList<String> arrayList = new ArrayList<>();
String s;
while ((s = br.readLine()) != null) {
arrayList.add(s);
}
int size = arrayList.size();
ints = new int[size][3];
int cou = 0;
for (String ss : arrayList) {
String[] strs = ss.split(" ");//这里划分用的空格!!!帅!!!!
for (int i = 0; i < 3; i++) {
ints[cou][i] = Integer.valueOf(strs[i]);
}
cou++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.把稀疏数组还原成二维数组
// 创建二维数组
int[][] chees = new int[ints[0][0]][ints[0][1]];
int c = ints[0][2];
// 把稀疏数组的数据还原回去 //多思考用普通的for循环可以指定从第几行开始循环,用增强for循环就难了
for (int i = 1; i <= c; i++) {
chees[ints[i][0]][ints[i][1]] = ints[i][2];
}
5.输出这个二维数组
System.out.println();
System.out.println("还原的二维数组为:");
for (int[] i : chees) {
for (int e : i) {
System.out.print(e + "\t");
}
System.out.println();
}
还原的二维数组为:
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0