私の要件は、System.inを介して8X8文字の値が与えられるチェスの問題を実行していたときに発生しました。私はそれをテストしていました、そして私はいつもかなり難しい64の入力を与えていました。さて、同じものをテキストファイルに保存し、それを読み取って文字配列に格納したいと思いました。私がそうするのを手伝ってください。ファイルの内容を読み取って表示する方法や、1D文字配列に変換する方法は複数あります。しかし、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
文字ごとに読むのではなく、行全体を直接読んで、後でそれをcharの配列に変換することをお勧めします
public static char[][] readChessFile(String filename) throws IOException {
char[][] input = new char[8][8];
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filename))) {
String line;
for (int i = 0; i < input.length; i++) {
line = bufferedReader.readLine();
if (line == null || line.length() != 8) {
throw new IllegalStateException("File is not in correct format");
}
input[i] = line.toCharArray();
}
}
return input;
}
そして、これが私のテストコードです
try {
char[][] result = readChessFile(filename);
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print(result[i][j]);
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加