Reading data from a text file and building a table with arrays

14,992

You could use an array of arrays to store what you need, like:

String[][] animal = new String[5][];

Then, when you read your file, store an array of all the values, like this:

while (input.hasNextLine() && index < animal.length) {
    animal[index] = input.nextLine().split(" "); //split returns an array
    index++;
}

Then, when you want to output, just loop over the array of arrays:

for (String[] a : animal)
{
    for (int i = 0; i < a.length; i++)
        System.out.print(a[i] + ", ");
    System.out.println("");
}
Share:
14,992
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin over 1 year

    I have an input file named "animals.txt":

    sheep 10.5 12.3 4
    horse 8.4  11.2 7
    cow   13.7 7.2  10
    duck  23.2 2.5  23
    pig   12.4 4.6  12
    

    To put my question simply, I would like to know how to store the 4 columns of data into 4 separate 1 dimensional arrays from the input file.

    The output should like something like this...

    [sheep, horse, cow, duck, pig]
    [10.5, 8.4, 13.7, 23.2, 12.4]
    [12.3, 11.2, 7.2, 2.5, 4.6]
    [4, 7, 10, 23, 12]
    

    So far I have figured out how to store all of the data into one large array, but I need to know how to break it down and store each column into its own array instead.

    My code:

    public static void main(String[] args) throws FileNotFoundException {
    
        String[] animal = new String[5];
        int index = 0;
    
        File file = new File("animals.txt");
        Scanner input = new Scanner(file);
    
        while (input.hasNextLine() && index < animal.length) {
            animal[index] = input.nextLine();
            index++;
        }