2017-04-21 41 views
-2

我有一個數組中的迷宮板,但似乎無法弄清楚如何將其保存爲一個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

'Arrays.toString(板)'不能很好與多維數組。改爲使用'Arrays.deepToString(board)'。 – Thomas

+0

剛剛嘗試過,仍然沒有打印哈哈 – A825

+0

[FileWriter的Java txt文件是空的]的可能重複(http://stackoverflow.com/questions/14060250/java-txt-file-from-filewriter-is-empty) – Tom

回答

0

有兩點需要指出:

打印出Java數組時
  1. ,你需要去通過他們,並打印每個元素 - 打印陣列println(board);的名字不會給你想要的結果。
  2. 當使用Printwriters寫入文件時,請記得關閉它們。

我還添加了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(); 
    }