public class Main {
public static void main(String[] args){
create("Maze.txt");
}
}
public class Maze {
private final int Max_Maze_Row=20;
private final int Max_Maze_Column=50;
public char[][] maze =new char[Max_Maze_Column-1][Max_Maze_Row-1];
public Maze(){
}
public void create(String filename) throws FileNotFoundException{
Scanner fileinput=new Scanner(new FileInputStream(filename));
fileinput.useDelimiter("");
while(fileinput.hasNextLine()){
int row=0;int col=0;
String line_content=fileinput.nextLine();
for(col=0;col<Max_Maze_Column;col++){
maze[row][col]=line_content.charAt(col);
}
row++;
fileinput.close();
}
System.out.println(maze);
}
}
所以基本上,我正在尝试创建一个迷宫类,它将从文本文件中读取 20x50 迷宫的内容(这将存储在 2d 数组中(。 我定义了方法创建,该方法将读取迷宫内容并创建 2D 数组。 我有它的代码,我认为这是正确的。 但是,当我在 main 函数中调用 create 方法时,出现"找不到符号"错误。另外,一旦我使create((方法成为静态方法,我就会得到非静态变量错误。为什么会这样? 有关错误的任何帮助或有关我的创建方法的提示将不胜感激。 谢谢。
在调用该类方法之前,必须创建该类的对象。 像这样:
public class Main {
public static void main(String[] args) {
Maze maze = new Maze();
maze.create("Maze.txt");
}
}
create
不是静态的,因此您需要一个Maze
的实例,例如:
new Maze().create("Maze.txt");
请注意,通常每个类都将位于不同的 java 文件中。
你的代码示例有一些"错误",但大多数是关于样式、模式等的,不一定是技术问题。
正如其他人所说,您需要创建一个Maze
类型的新对象才能调用create()
方法。
另一方面,为什么要调用一个 no-arg 构造函数,然后调用一个从磁盘加载迷宫的init
方法(这里称为create
(。相反,为什么不有一个Maze
构造函数来获取文件名并加载迷宫呢?
如果我正在设计这个类,我可能会像这样声明create
方法:
public static Maze load(String filename)
此方法将实例化一个新的Maze
对象,用数据填充它,然后将其返回给调用方。我喜欢这种"工厂模式",因为您可能希望以不同的方式实现Maze
。工厂方法比构造函数提供了更大的灵活性,因为工厂方法允许您返回所需的任何具体Maze
子类,并且您可以稍后改变主意。调用构造函数会将您锁定为使用该特定类。
与创建Maze
对象并调用其init
方法的方法完全无关,通过始终以最大允许大小分配char[][]
数组,您可能正在分配比必要的更多的堆内存。与其在对象构建时立即分配内存,也许你应该等到你知道迷宫会有多大。
如果迷宫文件说它是一个 10x10 的迷宫,你仍然分配了 49x20 个字符的数组,这比你实际需要的要多得多。
Maze
构造函数没有特别的理由不应该接受迷宫的大小作为参数,然后只分配所需的内存。
看到MAX_SIZE
这样使用很奇怪:
new char[MAX_SIZE - 1][MAX_SIZE - 1]
为什么要减去 1?通常,您会看到如下所示的分配:
new char[MAX_SIZE][MAX_SIZE]
然后像这样进行范围检查:
if(x <= maze.length - 1)
// x is in range
或
if(x < maze.length)
// x is in range
我希望这能帮助你建立一个更好的Maze
班。
尝试,
public class Main {
public static void main(String[] args){
**Maze.**create("Maze.txt");
}
}
public class Maze {
private final int Max_Maze_Row=20;
private final int Max_Maze_Column=50;
public char[][] maze =new char[Max_Maze_Column-1][Max_Maze_Row-1];
public Maze(){
}
public **static** void create(String filename) throws FileNotFoundException{
Scanner fileinput=new Scanner(new FileInputStream(filename));
fileinput.useDelimiter("");
while(fileinput.hasNextLine()){
int row=0;int col=0;
String line_content=fileinput.nextLine();
for(col=0;col<Max_Maze_Column;col++){
maze[row][col]=line_content.charAt(col);
}
row++;
fileinput.close();
}
System.out.println(maze);
}
}