java如何在二维字符数组的空单元格中插入占位符值
我需要能够从文件中提取文本并将其插入到二维字符数组中,任何额外的单元格都需要填充@字符。如果文本文件太长,则需要忽略任何不适合的字符。我目前的代码将文本放置在一个20行45列的字符数组中,但前提是文本文件正好是900字节
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();
}
}
}
# 1 楼答案
正如前面提到的一条评论,一个简单的方法是首先用占位符填充你的黑板,然后只覆盖所需的位置
另一种方法是使用获得的偏移量迭代数组的其余部分,用占位符填充
第三种(也可以说是更好的)方法是使用偏移量来限制对数组的访问(如果数组比实际文件大得多,这将大大加快)
编辑:我已经添加了所有3种方法的代码示例
我的第三个选项使用了一个新的“类”