我不明白为什么这个调用不起作用(Java)



Maze用方法:generateMaze(int width, int height)实例化一个2D布尔数组,该方法必须在Walker中使用。创建布尔值[][]的方法调用发生在Walker类

main

上。我的目标是用walk(Maze maze),调用布尔[][]-数组,方法的输入必须是迷宫对象,而不是实际的布尔[][].我不明白如何调用它,必须有一种方法来调用它与一个迷宫对象的对象实例。

public final class Maze{
public static boolean[][] generateMaze(int width, int height) {
boolean[][] mazeArray = new boolean[width][height];
for( int x = 0; x < width; x++ ) {
mazeArray[x][0] = true;
}
for( int y = 0; y < height; y++ ) {
mazeArray[0][y] = true;
}
return mazeArray;
}
public boolean[][] getBooleanArray() {
return generateMaze(2,2);
} 
}
public class Walker {
public static void main(String[] args) {
boolean[][] maze = Maze.generateMaze(2,2);
Walker walker = new Walker();
Maze mazeObj  = new Maze();
walker.walk( mazeObj );
}
public void walk(Maze maze) {
// This call doesnt work. Why?
System.out.println( mazeObj.maze[0][0] );
}
}

所提供的代码几乎一切都是错误的,就我所认为的,你试图实现boolean[][] maze应该是你的maze对象的实例变量,getBooleanArray()是完全多余的,你想要初始化一个新对象时完成的工作应该在构造函数下。此外,Maze类的最终声明在这种上下文中并没有真正的意义,但我不能对此发表评论,因为我不知道你的程序的其余部分。

下面提供了一个可能的修复和解释:

public class Maze{
/** Declare a new mazeArray instance variable (variables that are
*  attributes of specific instances of the class). It is common to
*  declare the instance variables private and manage access via
*  public accessor methods. See below for the accessor method.
*/
private boolean[][] mazeArray;

/** Move the contents of the generateMaze to the constructor,
*  constructors are called when a new object is being instantiated.
*  (basically when you call new <ClassName>()), you do not have to
*  return the mazeArray anymore as it will be accessed via an
*  accessor method.
*/
public Maze(int width, int height) {
mazeArray = new boolean[width][height];
for( int x = 0; x < width; x++ ) {
mazeArray[x][0] = true;
}
for( int y = 0; y < height; y++ ) {
mazeArray[0][y] = true;
}    
}
/** This is the accessor method that will be 
*  used by the outside world to access
*  the mazeArray field
*/
public getMazeArray() {
return mazeArray;
}
}

在面向对象编程方面,Walker类也是有缺陷的。

public class Walker {
public static void main(String[] args) {
/* Calling new Maze() create a Maze object with the private
* boolean[][] mazeArray that you can access with the same
* object's getMazeArray() method.
*/
Maze maze = new Maze();
walk(maze);
}
/** I don't know if you will have multiple Walker objects in your
*  program, depending on that decision you might want to make this
*  method non-static but for now this will suffice
*/
public static walk(Maze maze) {
boolean[][] mazeArray = maze.getMazeArray();
System.out.println(mazeArray[0][0]);
}
}

而且你似乎没有正确地使用Java,作为几年前在同一地方的人,我会推荐Head First Java作为开始阅读的好地方。此外,你可能想线性化你的2D数组,以防止以后的性能问题,这取决于你的项目的方向。

相关内容

  • 没有找到相关文章

最新更新