user6350038
user6350038

Reputation:

How to import .dat file into multiple arrays

Alright so I'm working on a program that reads a periodic table and you can search elements based on number or abbreviation.

Anyway, I'm a bit stuck trying to read the periodic table file into 4 different arrays: Atomic Number, Abbreviation, Element Name, and Atomic Weight.

I dunno how to write a single method to import all that info into each array in one go. I want to have a class that holds all these arrays and that I can call to later when I need each one.

Here is what I got so far, I'm a bit rusty by the way... I thought working on this program would refamiliarize me with the basics.

class PeriodicTable{
    private String fileName = "periodictable.dat";

    private int[]    atomicNumTable    = new int[200];
    private String[] abbreviationTable = new String[200];
    private String[] nameTable         = new String[200];
    private double[] atomicWeightTable = new double[200];

    PeriodicTable(String fileName){
        readTable(fileName);
    }

    public int[] readTable(String fileName){
        Scanner inFile = null;
        try{
            inFile = new Scanner(new File(fileName));
        }catch(FileNotFoundException nf){
            System.out.println(fileName + " not found");
            System.exit(0);
        }

        atomicNumTable = new int[200];
        int i = 0;
        while(inFile.hasNext() && i < atomicNumTable.length){
            int number = inFile.nextInt();
            atomicNumTable[i] = number;
            i++;
        }
        inFile.close();
        return atomicNumTable;
    }
}

Here is what each line of the table looks like:

1    H   Hydrogen    1.00794

Upvotes: 2

Views: 506

Answers (3)

GhostCat
GhostCat

Reputation: 140457

  1. Simply use java.lang.String.split(' ') (assuming that your columns are separated using spaces; if it is using something else; you just need to adapt that regular expression parameter!)
  2. That will return an array of Strings; and you basically now: first column should be an int, then you got two Strings, and then a double value. Or lets be precise: you get strings, that mean something else; thus you have to look into methods like Integer.valueOf(); and similar for Double.

Shouldn't be too hard to work your way from there.

But I recommend some changes to your logic: having 4 different tables doesn't make sense at all. Good OO programming is about creating helpful abstractions. Without abstractions, your program becomes abstract itself.

Meaning: you should introduce a class like

public class Element {
  private final int id;
  private final String abbreviation;
  private final String fullName;
  private final double atomicWeight;

  ... with one constructor that takes all 4 parameters

  ... with getter methods for the fields of this class

  ... and meaningful overrides for equals() and hashcode()

}

And then, instead of creating 4 arrays; you create one array, or even better an ArrayList<Element>. And instead of pushing your 4 values into 4 different arrays, you create one new Element object in each loop iteration; and you add that new object to your list.

The major difference to your solution would be: you can deal with Elements as a whole; whereas in your solution, a single "Element" is basically an index that points into 4 different tables.

Upvotes: 2

mm759
mm759

Reputation: 1424

You can distinguish four cases in the loop:

  • i%4 == 0

  • i%4 == 1

  • i%4 == 2

  • i%4 == 3

Depending on this you know the kind of next value you have to read. So, you can search you an integer, string or floating point number and put the value in the right place.

I support the recommendation of GhostCat to only have one array and a class that contains all four values of a line instead of having four arrays.

Upvotes: 0

Keshan Nageswaran
Keshan Nageswaran

Reputation: 8178

You can simplify this code a lot. Try something like this.

1) Read the file line by line, split lines as you go, add values to some ArrayList containing String[]

2) Close your file

3) Turn the ArrayList into a String[][]

4) Print the result

Also, note that arrays in Java are indexed starting at 0 not at 1.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;

public class Test {

    static public void main(String[] args) throws Exception {

        File file = new File("periodictable.dat");
        FileReader reader = new FileReader(file);
        BufferedReader buffReader = new BufferedReader(reader);
        String s = null;

        ArrayList<String[]> lst = new ArrayList<String[]>();
        String[][] res = null;

        while((s = buffReader.readLine()) != null){
            String[] arr = s.split("[\\s]+");
            lst.add(arr);
        }

        buffReader.close();

        res = new String[lst.size()][lst.get(0).length];
        res = lst.toArray(res);

        System.out.println();

        // System.out.println(res);

        // String result = Arrays.deepToString(res);
        // System.out.println(result);
        System.out.println();

        for (int i=0; i<res.length; i++){
            for (int j=0; j<res[i].length; j++){
                System.out.println("res[" + (i+1) + "][" + (j+1) + "]=" + res[i][j]);
            }
        }

        System.out.println();
    }

}

OUTPUT:

res[1][1]=1
res[1][2]=H
res[1][3]=Hydrogen
res[1][4]=1.00794

value iterates indexing for each line

Upvotes: 2

Related Questions