我需要从文本文件中获取字符,并将它们按行主序存储在 20 x 45 的 2D 字符数组中。然后,我需要打印出存储的字符列主序。这需要适用于任何大小的文本文件。这段代码是我所得到的,但我还无法将其打印出来。
package myfirstjavaproject;
import java.io.*;
import java.util.Scanner;
public class temp {
public static void main(String[] args)throws Exception{
File file = new File ("test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st = br.readLine();
int row = 20, column = 45;
int offset = 0;
char[][] array = new char [row][column];
for (int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
array[i][j] = st.charAt(offset++);
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
此代码将其打印出来,然后我收到一条错误消息。
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 55
at java.lang.String.charAt(Unknown Source)
at myfirstjavaproject.temp.main(temp.java:18)
最佳答案
/* 我认为您正在尝试以下操作:您可能想使用 stringbuilder 或 stringbuffer 而不是 String */
public static void main(String[] args)throws Exception{
File file = new File ("test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st = br.readLine();
String s = null;
while(br.read()!=-1)
{
s=s+br.readLine();
}
int row = 20, column = 45;
int offset = 0;
char[][] array = new char [row][column];
for (int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
array[i][j] = s.charAt(offset++);
System.out.print(array[i][j]);
}
System.out.println();
}
}
关于java - 如何用文本文件中的字符填充二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283869/