import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CSVReader {
public static void main(String[] args) {
CSVReader obj = new CSVReader();
obj.run();
}
public void run() {
String CSVFile = "/Users/Wyatt/CSVFile2.csv";
BufferedReader br = null;
String Line = "";
String analysisStr;
String CSVDelimiter = ",";
int analysis;
double AVGDate = 0;
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
try {
br = new BufferedReader(new FileReader(CSVFile));
while ((Line = br.readLine()) != null) {
String[] Weather = Line.split(CSVDelimiter);
System.out.println("Weather [Date: "
+ Double.parseDouble(Weather[0]) + ", Interval: "
+ Double.parseDouble(Weather[1]) + ", Rainfall: "
+ Double.parseDouble(Weather[2]) + ", Sunlight: "
+ Double.parseDouble(Weather[3]) + ", Time: "
+ Double.parseDouble(Weather[4]) + ", Total: "
+ Double.parseDouble(Weather[5]) + ", Overall: "
+ Double.parseDouble(Weather[6]) + "]");
AVGDate = (Double.parseDouble(Weather[0]) / 804);
System.out.println(AVGDate);
}
System.out.println("What data is wanted?");
analysisStr = console.readLine();
analysis = Integer.parseInt(analysisStr);
if(analysis == 0) {
System.out.println("Date.");
System.out.println("Minimum date is:");
System.out.println("Maximum date is:");
System.out.println("Average date is: " + AVGDate);
}
else if(analysis == 1) {
System.out.println("Interval.");
System.out.println("This data isn't useful.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done.");
}
}
上面的程序正确读取文件,读取并打印出所有记录,但是对于我的平均日期,它计算每个单独的记录日期而不是一起计算所有日期,我是新手用户,对Java来说真的很新,我我看不出自己做错了什么。另一个问题是我不知道如何计算每列的最小/最大数据。只是直截了当不确定如何做到这一点。
答案 0 :(得分:0)
要计算平均值,您必须先计算总数并将其除以元素数。因此,每次读取数据时,都会初始化total
并将其汇总到while循环中。
double total = 0.0
while(...) {
...
total += Double.parseDouble(Weather[0]);
}
AVGDate = total / 804;
现在关于计算最小值或最大值......
double minDate = Double.MAX_VALUE;
double maxDate = Double.MIN_VALUE;
while(...) {
// parse each data
double temp = Weather[0];
if(temp < minDate) {
minDate = temp;
}
else if(temp > maxDate) {
maxDate = temp;
}
}
还要记住,我们使用lower-case约定来进行非最终变量命名。