[英]How do I get individual characters from read in text file and store them into a 2D array?
所以我有一个看起来像这样的文本文件:
##oooooo
##oo#oo#
oo##o##o
oo##o##o
o#oo#oo#
oo##o##o
oo##o##o
o#oo#oo#
我想在中间插入一个大小为 10x10 的 2D 字符数组,其中包含“#”。 所以像这样。
##########
###oooooo#
###oo#oo##
#oo##o##o#
#oo##o##o#
#o#oo#oo##
#oo##o##o#
#oo##o##o#
#o#oo#oo##
##########
下面的代码首先打印出一个纯“#”的二维数组。 我继续读取文本文件并获取每行的单个字符并将它们设置为 i 和 j position 的 char 值。 到目前为止,这是我的代码......
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
char[][] hashArray = new char[10][10];
readFromFile("grid1.txt", hashArray);
}
public static void readFromFile(String txtFile, char[][] hashArray)
{
// Displays basic 10x10 array of #
int counter = 0;
for (int i = 0; i < hashArray.length; i++)
{
for (int j = 0; j < hashArray.length; j++)
{
if (counter == 10)
{
System.out.println();
counter = 0;
}
hashArray[i][j] = '#';
System.out.print(hashArray[i][j]);
counter++;
}
}
System.out.println("\n");
counter = 0;
for (int i = 0; i < hashArray.length; i++)
{
for (int j = 0; j < hashArray.length; j++)
{
// I use a counter to skip to next line
if (counter == 10)
{
System.out.println();
counter = 0;
}
// Basically creates my # borders
if ((i == 0) || (i == 9) || (j == 0) || (j == 9))
{
hashArray[i][j] = '#';
System.out.print(hashArray[i][j]);
counter++;
}
else
{
// counter set at 2 compensates for the length of
// each line of read in text file.
counter = 2;
try
{
Scanner read = new Scanner(new File(txtFile));
while (read.hasNext())
{
String grid = read.nextLine();
char value = grid.charAt(i);
hashArray[i][j] = value;
System.out.print(hashArray[i][j]);
counter++;
}
}
catch (FileNotFoundException fnf)
{
System.out.println("File was not found.");
}
}
}
}
System.out.println();
}
当我运行它时,它给了我这个错误。
java.lang.StringIndexOutOfBoundsException: String index out of range: 8
我感谢任何和所有的帮助。 谢谢。
您不只是想在输入的每一行的开头和结尾添加 append 和 hash 标签(#)吗?
如果是这样,这样不是更容易吗?
public static void main(String[] args) throws IOException {
Files.readAllLines(Paths.get("grid1.txt"))
.forEach(i -> System.out.println("#" + i + "#"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.