-2

我试着问过,但我想我以错误的方式提问。将硬编码的迷宫读入多维数组

我需要读取一个txt文件到二维数组中。

我的txt文件是一段代表墙壁,路径和外部的字符。

它是一个硬编码的迷宫,因此字符必须以与文件中相同的配置读入数组。

香港专业教育学院尝试多种方法,但我不能就换我的头周围 继承人的代码

public static void main(String[] args) { 
    File file = new File("//Mac//Users//Tucker//SPSU//Programming 2//mazehardcode"); 
    Scanner fileScanner = new Scanner(file); 
    String mazeCode = fileScanner.nextLine(); 
    char buffer [][]= new char[80][80]; 
    new Thread(new Monitor()).start(); 
    while (fileScanner.hasNextLine()){ 
    for(int i = 0;i<buffer.length;i++){ 
     for(int j = 0;j<buffer[i].length;j++){ 

     } 
    } 
    } 

这就是我能得到没有错误,所以我需要帮助 我得到要做的错误将字符串转换为char,或将char转换为char [] []或沿着这些行的任何内容。

回答

1

如果您tilemap的看起来像这样的文件:

11111 
10001 
11101 
10001 
11111 

您可以阅读通过每一个字符的每一行和循环,并将其分配给char buffer[][]

int currentLine = 0; 
while (fileScanner.hasNextLine()){ 

    String line = fileScanner.nextLine(); 
    for(int i = 0;i<line.length();i++){ 
     buffer[currentLine][i] = line.charAt(i); 
    } 
    currentLine++; 
} 

如果您存储它只有在这样一行:

1111110001111011000111111 

你可以做一些模和分裂。 编辑:只能如果tilemap的宽度是一样的缓冲

if(fileScanner.hasNextLine()){ 
    String line = fileScanner.nextLine(); 
    for(int i = 0;i<line.length();i++){ 
     buffer[i/buffer.length][i%buffer.length] = line.charAt(i); 
    } 
} 

但要注意的水平的实际大小的长度,所以也许你会在第一行的大小它的大小会有所不同。

0

如果您需要从文件中读取字符块,例如下面提到的示例。

######### 
#0000111# 
######### 

在将字符串转换为字符数组后,可以使用System.Arraycopy将整行复制到缓冲区中。

int lineCount=0; 
while (fileScanner.hasNextLine()){ 
    String line = fileScanner.nextLine();           
    System.arraycopy(line.toCharArray(),0,buffer[lineCount++],0,line.length()); 
}