想要读取.txt文件并将其加载到2D数组中,然后按原样打印

时间:2017-05-30 14:16:41

标签: java

在我必须读取.txt文件并将其放入2D数组的分配中工作。 注意是二维阵列。

然后我必须像它一样打印它。

.txt输入如下所示:

WWWSWWWW\n
WWW_WWWW\n
W___WWWW\n
__WWWWWW\n
W______W\n
WWWWWWEW\n

这是我目前的代码,我有一个错误,说它无法解决方法'添加'。可能与数组初始值设定项有关

public static void main(String[] args) throws FileNotFoundException {

  Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
  String[][] list = new list[][];
  while (s.hasNextLine()){
      list.add(s.nextLine());

  }
  s.close();
  System.out.println(list);


}

然后打印输出必须

WWWSWWWW
WWW_WWWW
W___WWWW
__WWWWWW
W______W
WWWWWWEW

有任何帮助吗?谢谢!

3 个答案:

答案 0 :(得分:1)

假设使用2D数组的原因是每个字符都保存在单独的String对象中。 如果我们对文本文件一无所知,我会这样实现:

public static void main(String[] args) throws FileNotFoundException {
  File textFile = new File("D:/trabalho/maze.txt");
  Scanner rowsCounter = new Scanner(textFile));

  int rows=0;
  while (rowsCounter.hasNextLine()) {
    rowsCounter.nextLine();
    rows++;
  }
  String[][] data = new String[rows][];

  Scanner reader = new Scanner(textFile);
  for (int i = 0; i < rows; i++) {
    String line = reader.nextLine();
    data[i] = new String[line.length()];
    for (int j = 0; j < line.length(); j++) {
      data[i][j] = line.substring(j, j+1);
    }
  }

  reader.close();
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < data[i].length; j++) {
      System.out.print(data[i][j]);
    }
    System.out.println();
  }
}

此实现可以处理未知行数和每行的未知长度。

答案 1 :(得分:0)

你走了!

public static void main(String[] str){

    Scanner s = null;
    try {
        s = new Scanner(new File("path\\text.txt"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      List<String> list = new ArrayList<String>();
      while (s.hasNextLine()){
          list.add(s.nextLine());

      }
      s.close();
      Iterator<String> itr= list.listIterator();

      while(itr.hasNext()){
          System.out.println(itr.next().toString());
      }

}

答案 2 :(得分:0)

如果您想坚持使用Array,可能的解决方案是

public static void main(String[] args) throws FileNotFoundException {

  Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
  String[][] list = new String[10][5];
  for(int x = x; s.hasNextLine();x++ ){
   for(int i = 0; i < 5 ; i++){
      list[x][i] = s.nextLine();
   }
 }
  s.close();
  System.out.println(list);

}

所以你甚至不需要2D数组这里因为String类在C ++中就像一个char数组。

另一种解决方案是使用ArrayLists

public static void main(String[] args) throws FileNotFoundException {

  Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
  ArrayList<String> list = new ArrayList<String>;
  while (s.hasNextLine()){
      list.add(s.nextLine());
  }
  s.close();
  System.out.println(list);
}

所以现在你有一个随着你的数据量而增长的列表,你也可以使用add方法。 行ArrayList<String>表示您的arrayList只能存储类String

中的数据