简体   繁体   中英

How to Load a file in parallel arrays in java

I have a file that contains 30 lines of data in this format:

month-day-year-gas price

Here's some sample data:

May 02, 1994 1.04

Can someone tell me how to load this file in a parallel arrays of months, days, price in java? After this I will have to display the lowest price, and also the highest price, and the average price for each month.

For those who are wondering:

Parallel Arrays are arrays where the data in each array is directly related to any given record data row. The index of one array contains related data at the very same index in another array. For example:

Dimension[] dim = new Dimension[4];
dim[0] = new Dimension(1,11);
dim[1] = new Dimension(2,22);
dim[2] = new Dimension(3,33);
dim[3] = new Dimension(4,44);

int[] widths = {dim[0].width, dim[1].width, dim[2].width, dim[3].width};
int[] heights = {dim[0].height, dim[1].height, dim[2].height, dim[3].height};

for (int i = 0; i < widths.length; i++) {
    int w = widths[i];
    int h = heights[i];
    System.out.println("Width: " + w + " | Height: " + h);
}

And the Console output would be:

Width: 1 | Height: 11
Width: 2 | Height: 22
Width: 3 | Height: 33
Width: 4 | Height: 44

The widths and heights Integer Arrays are considered Parallel Arrays since the data index in each array is directly Related To and Parallel to each other. It doesn't matter which parallel array you iterate through, the current iteration is related to all other parallel arrays.

You can quickly see why it's much better to utilize a Class with Member variables for this sort of thing instead of arrays especially when a multiple number of parallel arrays are involved however, there are some practical uses for it.

The task at hand:

As you read in your file you want to use the String#split() method to break that line into the desired chunks you want. The delimiter to use here for the split() method will be a white-space ( " " ) or the Regular Expression (RegEx) "\\\\s+" , for example:

   "This is my String".split("\\s+");

The RegEx argument within the split() method basically means, split the string on one or more white-spaces.

In the example below the Parallel Arrays are Class Member variables. The method that fills these Arrays with the pertinent data from file is named fillParallelArraysWithFileData() and it accepts one argument, which is the path and name of the data file. Here is the code:

private static String[] monthsArray;
private static int[] daysArray;
private static int[] yearsArray;
private static double[] pricesArray;

public static void fillParallelArrayWithFileData(final String filePath) {
    Scanner read = null;
    try {
        read = new Scanner(new File(filePath));
        /* First Read Pass 
           ===============
           Get the number of VALID data lines in file.
           We need this count to know how large to size
           our Parallel Arrays.
        */
        int lineCount = 0;  // counter
        while (read.hasNextLine()) {
            String line = read.nextLine().trim(); // Trim lead/trailing whitespaces (if any)
            /* Skip past blank or comment lines. Lines that start with
               a semicolon (;) or a hash character (#) are considered
               comment lines here and are ignored. You can get rid of 
               those conditions if you like.   */
            if (line.equals("") || line.startsWith(";") || line.startsWith("#")) {
                continue;
            }
            lineCount++;  // Increment the counter.
        }

        /* Second Read Pass 
           ================
           Get the file data and fill Arrays...
           Declare Arrays which will be our parallel arrays.  */
        monthsArray = new String[lineCount];
        daysArray = new int[lineCount];
        yearsArray = new int[lineCount];
        pricesArray = new double[lineCount];
        int indexIncrementer = 0;

        // Start the read from beginning again...
        read = new Scanner(new File(filePath));
        while (read.hasNextLine()) {
            String line = read.nextLine();
            // Remove the comma in data line. Don't want it.
            line = line.trim().replace(",", ""); 
            // If the current line is blank or a comment then skip past it.
            if (line.equals("") || line.startsWith(";") || line.startsWith("#")) {
                continue;
            }
            // Split the current data line
            String[] lineParts = line.split("\\s+");
            monthsArray[indexIncrementer] = lineParts[0];
            daysArray[indexIncrementer] = Integer.parseInt(lineParts[1]);
            yearsArray[indexIncrementer] = Integer.parseInt(lineParts[2]);
            pricesArray[indexIncrementer] = Double.parseDouble(lineParts[3]);
            indexIncrementer++;
        }

    }
    catch (FileNotFoundException ex) {
        System.out.println("FILE NOT FOUND! [" + filePath + "]");
    }
    finally {
        if (read != null) {
            read.close();
        }  
    }
}

And an example usage might be:

// Fill Arrays with File data.
fillParallelArrayWithFileData("GasPrices.txt");

// Get Gas price for month of July in 1994       
String desiredMonth = "July";
int desiredYear = 1994; 
// We could iterate through any one of the Parallel Arrays
for (int i = 0; i < pricesArray.length; i++) {
    if (monthsArray[i].equalsIgnoreCase(desiredMonth) && yearsArray[i] == desiredYear) {
        String m = "Date: " + monthsArray[i] + " ";
        String d = daysArray[i] + ", ";
        String y = yearsArray[i] + " - ";
        String p = "Gas Price:  $" + pricesArray[i];
        System.out.println(m + d + y + p);
    }
}

Output to console window would be something like:

Date: July 2, 1994 - Gas Price:  $1.12

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