简体   繁体   中英

java 2D array from text file

I am trying to make this input.txt into a 2D array. I tried a few different methods. This is my latest attempt, and I seem to be stuck here... Any help is much appreciated.

input.txt structure: SCI2000/Science/1200/10/C --> There are 23 rows and 5 columns. I'd also like to have a title made for each column.

    FileReader fr = new FileReader("input.txt");
    BufferedReader br = new BufferedReader(fr);
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
    String[][] input = new String[23][5];
    String[] tokens = everything.split("/");
    for(String str : tokens)
        System.out.print(str);

Just the main processing part (not tested):

int columns = 5; 
String[] row = String[columns];
int j = 0; 

while ((line = br.readline) != null) {
    row = line.split("/");
    for(int i=0; i<row.length; ++i) {
       input[j,i] = row(i);
    }
    ++j;
}
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
String[][] input = new String[24][5]; // 1 row for title, 23 rows for data

// add title
input[0] = new String[]{"title1", "title1", "title1", "title1", "title1"};
String line = br.readLine();
int row = 1; // update here

while ( (line = br.readLine())!= null ) {
    input[row++] = line.split("/");
}

// print all data
for ( int i = 0; i < input.length; i++) {
    for ( int j = 0; j < input[i].length; j++ )
        System.out.print(input[i][j] + " ");

    //new line
    System.out.println();
}

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