有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

正在做一项任务,我必须读一本书。txt文件,并按原样将其放入2D数组中注意ts必须是2D数组

然后我必须再次打印它

那个。txt输入如下所示:

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

这是我目前拥有的代码,我有一个错误,说它无法解析方法“add”。可能与数组初始值设定项有关

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

有什么帮助吗?谢谢


共 (2) 个答案

  1. # 1 楼答案

    给你

    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. # 2 楼答案

    如果你想继续使用你的阵列,一个可能的解决方案是

    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数组,因为^ {< CD1>}类在C++中像char数组一样运行。p>

    另一个解决方案是使用ArrayList

    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只能存储类字符串中的数据