如何将字符串文件读入二维数组

How do I read a file of strings into a 2d array

我正在读取的文件有 40 个不同的字符串,我想将它放在 2d-array 中,大小为 [10][4].

到目前为止的代码

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();
        } 

文本文件格式:

apple 
orange 
dog
cat

假设金额受到控制,那么您需要为 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++];
   }
}

但在这样做之前,我会阅读所有行并将它们放在一个 StringBuilder 中,可以是 splitvalidated 在这样做之前 looping.

你有两个选择,一个是 Scary Wombat 在上面描述的。

第二个是您可以创建一维数组,并将其视为二维数组。

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();
        } 
}
}