试图将数组打印为文件?

时间:2017-04-21 11:51:58

标签: java

我在阵列中有一个迷宫板,但似乎无法弄清楚如何将其保存为txt文件然后将其打印出来?

String [][] board = new String [][] {
        {"#","#","#"," "," ","#" ,"#","#","#"},
        {"#","#"," ","#"," ","#","#"," ","#"},
        {"#"," "," "," ","#"," "," "," "," "},
        {"#","#","#","#","#","#","#"," ","#"},
    };

    System.out.println(Arrays.toString(board));

    File boardFile = new File("board.txt");
    PrintWriter boardPW = new PrintWriter(boardFile);
    boardPW.println(board);
    Scanner scan = new Scanner(boardFile);
    while(scan.hasNextLine()) {
        System.out.println(scan.nextLine());

    }

我觉得这是完全错误但值得一试!哈哈

1 个答案:

答案 0 :(得分:0)

要指出两点:

  1. 在java中打印数组时,您需要浏览它们并打印每个元素 - 打印数组println(board);的名称将无法获得所需的结果。
  2. 使用Printwriters写入文件时,请记得关闭它们。
  3. 我还添加了try / catch块,但我假设您使用了抛出异常的方法?

    更新代码:

        String [][] board = new String [][] {
            {"#","#","#"," "," ","#" ,"#","#","#"},
            {"#","#"," ","#"," ","#","#"," ","#"},
            {"#"," "," "," ","#"," "," "," "," "},
            {"#","#","#","#","#","#","#"," ","#"},
        };
    
        File boardFile = new File("board.txt");
        try{
            PrintWriter boardPW = new PrintWriter(boardFile);
            for(int i = 0 ; i < board.length; i++){
                for(int j = 0 ; j < board[i].length; j++){
                    boardPW.print(board[i][j]);
                }
                boardPW.println();
            }
            boardPW.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    
        try{
            Scanner scan = new Scanner(boardFile);
            while(scan.hasNextLine()) {
                System.out.println(scan.nextLine());
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }