java - 如何在java中以并行数组加载文件
问题描述
我有一个文件,其中包含 30 行这种格式的数据:
月-日-年-gas 价格
以下是一些示例数据:
1994 年 5 月 2 日 1.04
有人能告诉我如何在java中以月、日、价格的并行数组加载这个文件吗?在此之后,我将不得不显示每个月的最低价格、最高价格和平均价格。
解决方案
对于那些想知道的人:
并行数组是每个数组中的数据与任何给定记录数据行直接相关的数组。一个数组的索引包含另一个数组中相同索引处的相关数据。例如:
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);
}
控制台输出将是:
Width: 1 | Height: 11
Width: 2 | Height: 22
Width: 3 | Height: 33
Width: 4 | Height: 44
宽度和高度整数数组被认为是并行数组,因为每个数组中的数据索引彼此直接相关和平行。您迭代哪个并行数组并不重要,当前迭代与所有其他并行数组相关。
您可以很快看到为什么使用带有成员变量的类而不是数组更好,特别是当涉及多个并行数组时,它有一些实际用途。
手头的任务:
当您在文件中阅读时,您想使用String#split()方法将该行分成所需的块。此处用于 split() 方法的分隔符将是空格 ( " " ) 或正则表达式(RegEx) "\\s+",例如:
"This is my String".split("\\s+");
split()方法中的 RegEx 参数基本上意味着,将字符串拆分为一个或多个空格。
在下面的示例中,并行数组是类成员变量。用文件中的相关数据填充这些数组的方法名为fillParallelArraysWithFileData(),它接受一个参数,即数据文件的路径和名称。这是代码:
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();
}
}
}
一个示例用法可能是:
// 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);
}
}
输出到控制台窗口将类似于:
Date: July 2, 1994 - Gas Price: $1.12
推荐阅读
- .net - 如果所有者窗口以编程方式关闭,WPF ShowDialog() 不会返回
- android - RecyclerView 将 Alpha 设置为所选项目
- php - Symfony 4:验证器正在刷新而不是显示消息
- elasticsearch - 每天与前一天的计数的 Delta (Difference)
- c - 结构分配大小中断 spi_sync_transfer
- flutter - 如果我使用过多的“const”关键字,会有什么不同吗?
- scala - 如何在 scala 中启用后缀运算符?
- ios - Xcode 11 beta 5 / iOS 13 Public Beta 7 Combine 在设备上崩溃但在模拟器中运行
- c# - android的触摸控件没有检测到我的X位置
- powershell - 尝试查找具有相同命名文件的文件夹