Я использую 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;
}
}
Проблема заключается в handleArguments()
с этой строкой (и другими ее копиями):
String mazefile = args[0];
Этот оператор объявляет и присваивает значение локальной переменной, которая затеняет (скрывает) поле с тем же именем.
Из спецификации языка Java, раздел 14.4.3:
Если имя, объявленное как локальная переменная, уже объявлено как имя поля, то внешнее объявление затеняется (§6.3.1) во всей области локальной переменной.
но в методе main()
вы передаете поле mazefile
для создания файла:
readMazeFile(mazefile);
но полевой mazefile
еще не назначен - то есть null
.
Если исправить проблему, присвойте args[0]
полю:
mazefile = args[0];
File file = new File(mazefile);
Конечно,mazefile
действителен?