我是编程新手,我的代码存在问题。 我首先将Maze对象初始化为null,因为我不知道哪个是用户的选择。它在createMaze()方法中初始化,但是当我调用printMaze时,它是null。
import java.util.Scanner;
public class Main {
public static final String EXITGAME = "EXIT";
public static final String PRINTBOARD = "PRINT";
public static final String CREATEMAZE = "UPLOAD";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Maze maze = null;
menu(maze,in);
}
private static void menu(Maze maze, Scanner in){
String option = in.nextLine();
while(option.toUpperCase() != EXITGAME){
switch(option.toUpperCase()){
case PRINTBOARD: printMaze(maze); break;
case CREATEMAZE: createMaze(in,maze); break;
}
System.out.println();
option = in.nextLine();
}
}
private static void printMaze(Maze maze){
if(maze != null){
int maxX = maze.getxSize();
int maxY = maze.getySize();
for(int x = 0; x < maxX; x++){
for(int y = 0; y < maxY; y++){
System.out.print(maze.getMazeRepresentation(x, y));
}
System.out.println();
}
}
else
System.out.println("Maze is undefined");
}
private static void createMaze(Scanner in, Maze maze){
if(maze == null || !maze.getGameStatus()){
int x = in.nextInt();
int y = in.nextInt();
in.nextLine();
char rawMaze[][] = new char[x][y];
maze = new MazeClass(x,y);
for(int i = 0; i < x; i++){
createMazeLine(in,i,y, rawMaze);
}
maze.createMaze(rawMaze);
}
else
System.out.println("Maze already defined.");
}
private static void createMazeLine(Scanner in, int lines, int y, char[][] rawMaze){
String line = in.nextLine();
for(int i = 0; i < y; i++){
rawMaze[lines][i] = line.charAt(i);
}
}
}
答案 0 :(得分:0)
(即迷宫迷宫createMaze(Scanner in, Maze maze)
它是迷宫的参考值。
换句话说就是你的情况:
Java没有“引用参数”或指针概念。
因此,当您在方法createMaze
内进行maze = new MazeClass(x,y);
将新对象迷宫引用分配给引用参数变量。
但是你的初始null值和方法之外的引用保持不变,你在方法内部创建的对象在方法完成后被破坏。
简而言之,您只需要:
private static void menu(Maze maze, Scanner in){
String option = in.nextLine();
while(option.toUpperCase() != EXITGAME){
switch(option.toUpperCase()){
case PRINTBOARD: printMaze(maze); break;
case CREATEMAZE: maze = createMaze(in,maze); break;
}
System.out.println();
option = in.nextLine();
}
}
private static Maze createMaze(Scanner in, Maze maze){
if(maze == null || !maze.getGameStatus()){
... yuor code ...
maze.createMaze(rawMaze);
}
else
System.out.println("Maze already defined.");
return maze;
}
当然代码可以用更清晰的方式编写,但重点是
对方法内部方法参数的新值赋值不会替换在调用者中作为参数传递的变量值