简体   繁体   English

如何在java中以并行数组加载文件

[英]How to Load a file in parallel arrays in java

I have a file that contains 30 lines of data in this format:我有一个包含以下格式的 30 行数据的文件:

month-day-year-gas price月日年气价

Here's some sample data:以下是一些示例数据:

May 02, 1994 1.04 1994 年 5 月 2 日 1.04

Can someone tell me how to load this file in a parallel arrays of months, days, price in java?有人能告诉我如何在 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.当您读入文件时,您希望使用String#split()方法将该行分成所需的块。 The delimiter to use here for the split() method will be a white-space ( " " ) or the Regular Expression (RegEx) "\\\\s+" , for example:此处用于 split() 方法的分隔符将是空格 ( " " ) 或正则表达式(RegEx) "\\\\s+" ,例如:

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

The RegEx argument within the split() method basically means, split the string on one or more white-spaces. split()方法中的 RegEx 参数基本上意味着,将字符串拆分为一个或多个空格。

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.使用文件中的相关数据填充这些数组的方法名为fillParallelArraysWithFileData() ,它接受一个参数,即数据文件的路径和名称。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM