繁体   English   中英

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

[英]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 ,可以在执行此循环之前将其拆分验证

您有两种选择,一种是可怕的袋熊在那里描述的。

第二个是可以创建一维数组,并将其视为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++];
  }
}

我认为最有效的答案。 在这里你发现

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM