我在阵列中有一个迷宫板,但似乎无法弄清楚如何将其保存为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());
}
我觉得这是完全错误但值得一试!哈哈
答案 0 :(得分:0)
要指出两点:
println(board);
的名称将无法获得所需的结果。我还添加了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();
}