简体   繁体   中英

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] .

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

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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