2017-04-21 7 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

2つのことを指摘します

  1. Javaでの配列をプリントアウトし、あなたがそれらを通過し、各要素に印刷する必要があります - あなたの望ましい結果が得られないであろう配列println(board);の名前を印刷します。
  2. プリントライターを使用してファイルに書き込むときは、必ず閉じてください。

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(); 
    } 
関連する問題