涉及的相关知识点有,一维数组的创建,一维数组的打乱排序,一维数组转化为二维数组,switch()的使用。
package demo;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 1, 2, 3, 4, 0, 6, 7, 8, 5 };
int[] crr = { 1, 2, 3, 4, 0, 6, 7, 8, 5 }; //保留原始数据
System.out.println(Arrays.toString(crr));
System.out.println();
Random r = new Random();
int k = 0;
/**
* 打乱一维数组
**/
while (k < 20) {
int i = r.nextInt(8);
int j = r.nextInt(8);
int t = a[i];
a[i] = a[j];
a[j] = t;
k++;
}
System.out.println(Arrays.toString(a));
System.out.println("--------------");
int b[][] = new int[3][3];//定义二维数组
/*
* 一维转二维
*/
for (int i = 0; i < a.length; i++) {
b[i / 3][i % 3] = a[i];
}
for (int j = 0; j < b.length; j++) {
System.out.println(Arrays.toString(b[j]));
}
System.out.println("------------------");
/*
* 尋找0
*/
int indexX = 0;//二維行下標
int indexY = 0;//二維列下標
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
if (b[i][j] == 0) {
indexX = i;
indexY = j;
break;
}
}
}
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入w上移,s下移,a左移,d右移");
String ch = sc.next();
switch (ch) {
case "w":
if (indexX > 0) {
int t = b[indexX][indexY];
b[indexX][indexY] = b[indexX- 1][indexY ];
b[indexX- 1][indexY ] = t;
indexX--;
}
break;
case "s":
if (indexX < b.length - 1) {
int t = b[indexX][indexY];
b[indexX][indexY] = b[indexX+ 1][indexY ];
b[indexX+ 1][indexY ] = t;
indexX++;
}
break;
case "a":
if (indexY >0) {
int t = b[indexX][indexY];
b[indexX][indexY] = b[indexX][indexY - 1 ];
b[indexX][indexY -1] = t;
indexY--;
}
break;
case "d":
if (indexY < b.length -1) {
int t = b[indexX][indexY];
b[indexX][indexY] = b[indexX][indexY + 1 ];
b[indexX][indexY + 1] = t;
indexY++;
}
break;
}
for (int j = 0; j < b.length; j++) {
System.out.println(Arrays.toString(b[j]));
}
/*
* 判斷是否拼圖成功
*/
int g = 0;//一維下標
boolean flag = true;
for(int i = 0 ; i < b.length && flag; i++){
for(int j = 0; j < b[i].length; j++){
if( b[i][j] != crr[g]){
flag = false;
//System.out.println(crr[g]);
System.out.println("拼图失败");
break;
}
g++;
}
}
if(flag){
System.out.println("拼图成功");
break;
}
}
}
}