[英]How do I read a file of strings into a 2d array
The file I'm reading from has 40
different strings and I want to put it in a 2d-array
with a size of [10][4]
. 我正在读取的文件具有40
不同的字符串,我想将其放入2d-array
,其大小为[10][4]
。
code so far 到目前为止的代码
public class GetAnswers {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("Answers.txt")))
{
String [][] answers;
answers = new String[10][4];
String line;
int i = 0;
String [] temp;
while ((line = br.readLine()) != null) {
temp = line.split("\n");
for (int j = 0; j < answers[i].length; j++)
{
answers[i][j] = temp[j];
System.out.println(j);
}
i++;
}
//System.out.println(answers[1][2]);
} catch (IOException e) {
e.printStackTrace();
}
text file format: 文本文件格式:
apple
orange
dog
cat
Assuming that the amounts are controlled then you need to create a separate index for temp
and also have a inner for
loop 假设数量是受控的,那么您需要为temp
创建一个单独的索引,并且还需要一个内部for
循环
int x = 0;
for (int i = 0; i < 10; i++) { // outer
for (int y = 0; y < 4; y++) { // inner
answers [i][j] = temp[x++];
}
}
But before doing this I would read all lines and put them in a single StringBuilder
which can be split and validated before doing this looping . 但是在执行此操作之前,我将读取所有行并将它们放在单个StringBuilder
,可以在执行此循环之前将其拆分和验证 。
You got two options, one is what Scary Wombat described up there. 您有两种选择,一种是可怕的袋熊在那里描述的。
The 2nd one is you can create a 1D array, and treat it as 2D array. 第二个是可以创建一维数组,并将其视为2D数组。
answers = new int[40];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 4; j++) {
answers [i*10 + j] = temp[x++];
}
}
Most Effiecient Answer I Think. 我认为最有效的答案。 Here you found 在这里你发现
import java.io.*;
public class GetAnswers {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("GetAnswers.txt")))
{
String [][] answers;
answers = new String[10][4];
String line;
int i = 0;
String [] temp = new String [40];
while ((line = br.readLine()) != null) {
temp[i++] = line;
}
for(int j=0; j<temp.length; j++){
answers[j/4][j%4] = temp[j];
System.out.println(answers[j/4][j%4]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.