![](/img/trans.png)
[英]Read a text file (containing characters) & store it in a 2D array in java
[英]populating and printing a 2D array given text file containing characters
我试图从文本文件中提取文本文件后将其打印成网格格式。 与此方法类似,创建2级循环遍历每一行和每一列。 但是,我不确定在处理字符而不是数字时该过程有何不同。
8 10
+-+-+-+-+-+-+-+-+-+
| |
+ +-+-+-+ +-+-+-+ +
| | | |
+ + +-+-+-+-+-+ + +
| | | | | |
+ + + +-+-+-+ + + +-+
| | | | | | | S|
+ + + + +-+ + + + +-+
| | | |E| | | |
+ + + +-+ +-+ + + +
| | | | | |
+ + +-+-+-+-+-+ + +
| | | |
+ +-+-+-+-+-+-+-+ +
| |
+-+-+-+-+-+-+-+-+-+
static void readMazeFile(String mazefile) throws FileNotFoundException {
Scanner mazeIn = new Scanner (new File (mazefile));
int height = mazeIn.nextInt();
int width = mazeIn.nextInt();
System.out.print(width);
System.out.print(height);
// get array height & width
int arrayHeight = (height*2)+1;
int arrayWidth = (width*2)+1;
System.out.print(arrayHeight);
System.out.print(arrayWidth);
// create new array set variables
char mazeAsArray[][] = new char[arrayHeight][arrayWidth];
int charCount = 0;
//populate and print array
System.out.print("-------------\n");
for (int r = 0; r < 9; r++){
for (int c = 0; c < 9; c++){
System.out.print(mazeAsArray[r][c]);
}
}
}
谢谢
在该链接中可以回答大多数问题。 首先,您没有在数组中分配任何内容。 我将从此处的链接复制我的答案。
for (int row = 0; row < arrayheight; row++)
{
if(!mazein.hasNextLine())
break; // if there is no more lines to read, break the loop
String line = mazein.nextLine();
Char[] chars = line.toCharArray();
for (int col = 0, i = 0; (col < arraywidth && i < chars.length); col++,i++)
{
mazeAsArray[row][col] = chars[i];
System.out.print(mazeAsArray[row][col]);
}
}
更新:我发现您的文件每行中没有固定的字符数。 您必须计算高度的行数和宽度的最长行的字符数,也可以自己输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.