简体   繁体   中英

I read my text file, now how do I store the values into a 2D array?

As mentioned, I already managed to read in the file, I'm looking for a method to added to a 2D array. This is what I read:

20 10 8

4.5 8.45 12.2

8.0 2.5 4.0

1.0 15.0 18.0

3.5 3.5 3.5

6.0 5.0 10.0

import java.io.*;
import java.util.*;
public class Packages 
{

    public static void main(String[] args)throws IOException,FileNotFoundException
    {
        BufferedReader reader = new BufferedReader(new FileReader("Dimensions.txt"));
        while (true) 
        {
            String line = reader.readLine();
            if(line==null);
            {
                 break;
            }
        System.out.println(line);

        }
        reader.close();  
    }

}

  1. Create a scanner to read the line, Scanner scanner = new Scanner(line) .
  2. Create a loop that reads next item, scanner.next() or scanner.nextDouble() while it has next.
  3. Put each into array at its given spot by maintaining a count for lineNumber and doubleCount . If you do not know the dimension size you will have to do a loop that counts each line and another that counts how many doubles in the line.

The following solution uses a 2D array to store the numbers from your file. This would be an appropriate solution if the structure of your input is both known and well-defined. By this I mean that every row has three numbers, and you also know how many rows there are. If not, then you might want to use a Java collection class instead here.

public static void main(String[] args) throws IOException, FileNotFoundException {
    // change this value to whatever row count you actually have
    int NUM_ROWS = 100;
    double[][] array = new double[NUM_ROWS][3];
    BufferedReader reader = new BufferedReader(new FileReader("Dimensions.txt"));

    int counter = 0;
    while (true) {
        String line = reader.readLine();
        if (line == null) break;
        String[] parts = line.trim().split("\\s+");
        for (int i=0; i < 3; ++i) {
            array[counter][i] = Double.parseDouble(parts[i]);
        }

        System.out.println(line);
        ++counter;
    }
    reader.close();  
}

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