我无法将字符从文件中放入2d数组中。当我打印出阵列时,我得到了null
,我不知道为什么。将字符从文件逐行读入到2d数组
程序读入一个文件,格式化为第一行,包含2个数字,分别对应于高度和宽度,它首先检查命令行参数是否有效。如果是,则读取该文件,根据这两个数字创建一个2d数组,然后将该文件的其余部分存储到该数组中。该文件的其余部分是字符的迷宫,像这样:
2 3
+-+-+-+
|S| |
+ + + +
| |E|
+-+-+-+
所以,2D阵列模仿迷宫结构。方法readMazeFile
是我挣扎的地方。
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MazeSolver {
// The name of the file describing the maze
static String mazefile;
static int width;
static int height;
static int arrayWidth;
static int arrayHeight;
static char[][] mazeArrays;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args)) {
readMazeFile(mazefile, arrayHeight, arrayWidth);
System.out.println(Arrays.deepToString(mazeArrays));
//DrawMaze.draw(mazeArrays, height, width);
if (solveMaze())
System.out.println("Solved!");
else
System.out.println("Maze has no solution.");
}
else {
System.out.println("The arguments are invalid.");
}
}
// Handle the input arguments
static boolean handleArguments(String[] args) {
if (args.length > 4 || args.length < 1) {
System.out.println("There are too many or too few command line arguments");
return false;
}
if (args.length == 1) {
mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
return true;
}
if (args.length == 2) {
mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
int cellsize = Integer.parseInt(args[1]);
if (cellsize < 10) {
return false;
}
return true;
}
if (args.length == 3) {
mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
int cellsize = Integer.parseInt(args[1]);
int borderwidth = Integer.parseInt(args[2]);
if (borderwidth < 5) {
return false;
}
return true;
}
if (args.length == 4) {
mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
int cellsize = Integer.parseInt(args[1]);
int borderwidth = Integer.parseInt(args[2]);
int sleeptime = Integer.parseInt(args[3]);
if (sleeptime < 0 || sleeptime > 10000) {
return false;
}
return true;
}
return false;
}
// Read the file describing the maze.
static void readMazeFile(String mazefile, int arrayHeight, int arrayWidth) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(mazefile));
height = scanner.nextInt();
width = scanner.nextInt();
arrayHeight = 2 * height + 1;
arrayWidth = 2 * width + 1;
char[][] mazeArrays = new char[arrayHeight][arrayWidth];
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
for (int row = 0; row < arrayHeight; row++) {
for (int col = 0; col < line.length(); col++) {
mazeArrays[row][col] = line.charAt(col);
}
}
}
}
// Solve the maze.
static boolean solveMaze() {
return true;
}
}
这里是输出:
+-+-+-+
|S| |
+ + + +
| |E|
+-+-+-+
null
Solved!
感谢您的帮助,我对任何业余瑕疵道歉,我想学习Java。我想保持这种结构。在此之后,我必须使用2d数组来通过递归对迷宫的解决方案进行动画制作。从readMazeFile