我正在使用jgrasp,我不确定为什么我会收到此错误。具体做法是:
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(File.java:277)
at MazeSolver.readMazeFile(MazeSolver.java:87)
at MazeSolver.main(MazeSolver.java:15)
我尝试重写扫描仪部件,但我不知道我在做什么。我会在行号中加上评论。这是我的代码:
public class MazeSolver {
// The name of the file describing the maze
static String mazefile;
static int width;
static int height;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args)) {
readMazeFile(mazefile); //line 15
DrawMaze.draw();
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) {
String mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
return true;
}
if (args.length == 2) {
String 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) {
String 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) {
String 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 char[][] readMazeFile(String mazefile) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(mazefile)); //line 87
height = scanner.nextInt();
width = scanner.nextInt();
int arrayHeight = 2 * height + 1;
int 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 < arrayWidth; col++) {
mazeArrays[row][col] = line.charAt(col);
}
}
}
return mazeArrays;
}
// Solve the maze.
static boolean solveMaze() {
return true;
}
}
答案 0 :(得分:1)
问题出在handleArguments()
这行(及其他副本):
String mazefile = args[0];
此语句声明并为局部变量赋值,该阴影(隐藏)同名的字段。< / p>
来自Java语言规范,section 14.4.3:
如果声明为局部变量的名称已经声明为字段名称,那么该外部声明将在局部变量的整个范围内被遮蔽(第6.3.1节)。
但在main()
方法中,您传递了字段 mazefile
来创建文件:
readMazeFile(mazefile);
但字段mazefile
仍然未分配 - 即null
。
如果要解决问题,请将args[0]
分配到字段:
mazefile = args[0];