当我做一个象棋问题时,我的要求就来了,其中通过System.in给出了8X8字符值。我一直在测试它,并且每次我都提供64个输入,这非常困难。现在,我想将其保留在文本文件中,然后读取并存储在字符数组中。请帮我这样做。那些只是读取和显示文件内容的方式有很多种,或者我们可以将其转换为一维char数组。但是,我想知道它可以直接从StringBuilder转换为2D字符数组!这是我尝试过的。
StringBuilder c = new StringBuilder();
File f = new File("file\\input.txt");
FileInputStream br = new FileInputStream(f);
int str;
while ((str = br.read()) != -1) {
c.append((char) str);
}
br.close();
System.out.println(c);
int strBegin = 0;
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
input[i][j] = c.substring(strBegin,strBegin + 1).toCharArray()[0];
strBegin++;
}
}
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
System.out.print(input[i][j] + " ");
}
System.out.println();
}
在这里,文件input.txt的内容:
2345678
1 345678
12 45678
123 5678
1234 678
12345 78
123456 8
1234567
注意:数组中也必须存储一个对角线空间。
运行代码时,我得到了:
2345678
1 345678
12 45678
123 5678
1234 678
12345 78
123456 8
1234567
2 3 4 5 6 7 8
1 3 4 5 6
8
1 2 4
6 7 8
1 2
5 6 7 8
1 2 3 4 6 7 8
1 2 3 4 5
8
1 2 3 4