Java数组操作全解析:从多维数组到实用工具类
立即解锁
发布时间: 2025-08-18 00:27:50 阅读量: 13 订阅数: 25 


Java编程入门与实战指南
### Java数组操作全解析:从多维数组到实用工具类
#### 1. 多维数组的初始化与处理
在Java中,除了常见的一维数组,还可以使用多维数组。例如,对于三维数组,可以使用嵌套的`if`语句进行处理。下面是一个将数字1到27初始化到三维数组的示例:
```java
int[][][] threeD2 = new int[3][3][3];
int value = 1;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int k = 0; k < 3; k++)
threeD2[i][j][k] = value++;
```
这个代码通过三层嵌套的`for`循环,将`value`的值依次赋给三维数组的每个元素,并且每次赋值后`value`自增1。
#### 2. 有趣的示例:棋盘上骑士的移动
接下来,我们通过一个有趣的示例——棋盘上骑士的移动,来进一步了解二维数组的应用。
##### 2.1 问题描述
国际象棋棋盘是一个8×8的方格,骑士的移动规则是先向一个方向移动两格,然后转90度再移动一格。程序的目的是根据用户输入的骑士起始位置,计算并显示骑士可能的移动位置,同时以图形化的方式展示棋盘。
##### 2.2 代码实现
```java
import java.util.Scanner;
public class KnightMoves {
static Scanner sc = new Scanner(System.in);
static int[][] moves = { {-2, +1},
{-1, +2},
{+1, +2},
{+2, +1},
{+2, -1},
{+1, -2},
{-1, -2},
{-2, -1} };
public static void main(String[] args) {
System.out.println("Welcome to the "
+ "Knight Move calculator.\n");
do {
showKnightMoves();
} while (getYorN("Do it again?"));
}
public static void showKnightMoves() {
int[][] board = new int[8][8];
String kSquare;
Pos kPos;
do {
System.out.print("Enter knight's position: ");
kSquare = sc.nextLine();
kPos = convertSquareToPos(kSquare);
} while (kPos == null);
board[kPos.x][kPos.y] = 1;
System.out.println("\nThe knight is at square "
+ convertPosToSquare(kPos));
System.out.println(
"From here the knight can move to:");
for (int move = 0; move < moves.length; move ++) {
int x, y;
x = moves[move][0];
y = moves[move][1];
Pos p = calculateNewPos(kPos, x, y);
if (p != null) {
System.out.println(convertPosToSquare(p));
board[p.x][p.y] = 2;
}
}
printBoard(board);
}
public static Pos convertSquareToPos(String square) {
int x = -1;
int y = -1;
char rank, file;
file = square.charAt(0);
if (file == 'a') x = 0;
if (file == 'b') x = 1;
if (file == 'c') x = 2;
if (file == 'd') x = 3;
if (file == 'e') x = 4;
if (file == 'f') x = 5;
if (file == 'g') x = 6;
if (file == 'h') x = 7;
rank = square.charAt(1);
if (rank == '1') y = 0;
if (rank == '2') y = 1;
if (rank == '3') y = 2;
if (rank == '4') y = 3;
if (rank == '5') y = 4;
if (rank == '6') y = 5;
if (rank == '7') y = 6;
if (rank == '8') y = 7;
if (x == -1 || y == -1) {
return null;
} else {
return new Pos(x, y);
}
}
public static String convertPosToSquare(Pos p) {
String file = "";
if (p.x == 0) file = "a";
if (p.x == 1) file = "b";
if (p.x == 2) file = "c";
if (p.x == 3) file = "d";
if (p.x == 4) file = "e";
if (p.x == 5) file = "f";
if (p
```
0
0
复制全文
相关推荐










