繁体   English   中英

如何从文件读取到2d char数组

[英]How to read from File into 2d char Array

我试图弄清楚如何从看起来像这样的txt中读取内容:

12  
12  
WWWWWWWWWWWW   
W3000000000W  
W0000000000W  
W0000000000W   
W0000000000W  
W0000000000W  
W0000000040W  
W0000000000W  
W0000000000W  
W0000000000W  
W0000000000W  
WWWWWWWWWWWW  

放入一个String[][] ;

前两行是String[][]的大小。 这是说的代码

线程“ AWT-EventQueue-0”中的异常java.lang.ArrayIndexOutOfBoundsException:映射[i] [j] = temp [j] .toString()处为1;

public String[][] read() throws IOException{
    BufferedReader br = new BufferedReader(new FileReader("D:/College/Java Eclipse/Map.txt"));   
    String line = " ";


    int columnCount = Integer.parseInt(br.readLine());
    int rowCount = Integer.parseInt(br.readLine()); 

    String[] temp;
    String[][] map = new String[rowCount][columnCount];

    while ((line = br.readLine())!= null){ 
        temp = line.split("\\s+"); 

        for(int i = 0; i<rowCount; i++) {
            for (int j = 0; j<columnCount; j++) {    
                map[i][j] = temp[j].toString();
            }
        }

    }
    br.close();
    return map;

}

我不知道怎么了?

您的正则表达式 line.split("\\\\s+")返回单个String并且您就像在循环一样返回12个元素的数组(在您的情况下); 而且无论如何,您一次又一次地替换所有值,因为您正在读取第一个for循环之外的内容。

尝试这样的事情:

public static String[][] read() throws IOException {
  BufferedReader br = new BufferedReader(new FileReader("D:/College/Java Eclipse/Map.txt"));
  int columnCount = Integer.parseInt(br.readLine());
  int rowCount = Integer.parseInt(br.readLine());
  String[][] map = new String[rowCount][columnCount];

  for (int i = 0; i < rowCount; i++) {
    String line = br.readLine();

    for (int j = 0; j < columnCount; j++) {
      map[i][j] = String.valueOf(line.charAt(j));
    }
  }
  br.close();
  //System.out.println(Arrays.deepToString(map));
  return map;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM