最简单的方法是使用ArrayList<char[]>
. 您所要做的就是char[]
为每个新行添加一个新的读取:
ArrayList<char[]> chars = new ArrayList<>();
while (inputFile.hasNext()){
chars.add(inputFile.nextLine().toCharArray());
}
char[][] array = chars.toArray(new char[chars.size()][]);
AnArrayList
基本上是一个可变大小的数组。此代码获取文件中的每一行,将其转换为char[]
,然后将其添加到ArrayList
. 最后,它将 转换ArrayList<char[]>
为char[][]
.
如果您不能或不想使用ArrayList
,您可以随时这样做:
char[][] array = new char[1][];
int a = 0;
while(inputFile.hasNext()){
//read line and convert to char[]; store it.
array[a] = inputFile.nextLine().toCharArray();
//if there are more lines, increment the size of the array.
if (inputFile.hasNext()){
//create a clone array of the same length.
char[][] clone = new char[array.length][];
//copy elements from the array to the clone. Note that this can be
//done by index with a for loop
System.arraycopy(array, 0, clone, 0, array.length);
//make array a new array with an extra char[]
array = new char[array.length + 1][];
//copy elements back.
System.arraycopy(clone, 0, array, 0, clone.length);
a++;
}
}
如果您事先知道数组的尺寸:
char[][] array = new char[dimension_1][];
int a = 0;
while (inputFile.hasNext()){
array[a] = inputFile.nextLine().toCharArray();
a++; //don't need to check if we need to add a new char[]
}
回应评论:
我们知道 achar[][]
不能打印Arrays.toString()
(如果我们想要内容),因为我们会得到很多char[].toString()
. 但是,char[][]
可以使用以下方法之一打印 a:
public static String toString(char[][] array){
String toReturn = "[\n";
for (char[] cArray: array){
for (char c: cArray){
toReturn += c + ",";
}
toReturn += "\n";
}
return toReturn + "]";
}
我个人更喜欢这个(需要import java.util.Arrays
):
public static String toString(char[][] array){
String toReturn = "[\n";
for (char[] cArray: array){
toReturn += Arrays.toString(cArray) + "\n";
}
return toReturn + "]";
}