Read .txt file into 2D Array

前端 未结 4 1647
甜味超标
甜味超标 2020-11-28 12:21

There are a few of these topics out there, but this problem has a slight twist that makes it different.

I\'m focused on only half of a larger problem. I\'m sure man

4条回答
  •  迷失自我
    2020-11-28 12:46

    You're close, but change your while loop to look like the following:

    while (in.hasNextLine()) {
        Scanner lineIn = new Scanner(line);
        //The initial case - this first line is used to determine the size of the array
        if(lineIn.hasNext()) {
            //Create a String array by splitting by spaces
            String[] s = lineIn.nextLine().split(" ");
            //Reinitialize the array to hold all of your subarrays
            matrix = new int[s.length];
            for (int i = 0; i < s.length; i++) {
                //Reinitialize each subarray to hold the numbers
                matrix[i] = new int[i];
                //Finally, parse your data from the String array
                matrix[0][i] = Integer.parseInt(s[i]);
            }
        }
        //Repeat the steps now that all of your arrays have been initialized
        for (int j = 1; j < matrix.length; j++) {
            String[] s = lineIn.nextLine().split(" ");
            for (int i = 0; i < s.length; i++) {
                matrix[j][i] = Integer.parseInt(s[i]);
            }
        }
    }
    

    The biggest change that you can make to make this easier on yourself is to get your numbers line-by-line. With each line you get, it's easy to then split it into a String array so that you can parse each number separately. Doing it this way you can then get the full length of the array all at once without having to have troublesome counters.

提交回复
热议问题