我的程序正在读取CSV并将数据输入到数组中。一旦数据存储到数组中,我想修改数据以找到某些计算,例如平均值,最大值和最小数量。
我根本看不出我出错的地方......我确信这很简单。任何帮助将不胜感激!
public class calculation {
public static void main(String[] args) throws IOException {
double year[] = new double [804];
double month[] = new double [804];
double tmax[] = new double [804];
double tmin[] = new double [804];
double af[] = new double [804];
double rain[] = new double [804];
double sun[] = new double [804];
double tavg[] = new double[804];
double sumYear = 0;
double sumMonth = 0;
double sumTmin = 0;
double sumTmax = 0;
double sumRain = 0;
double sumAF = 0;
double sumSun = 0;
int counter = 0;
//CREATE BUFFERED READER TO READ DATA
try {
BufferedReader file = new BufferedReader(new FileReader("data.csv"));
String line="";
//Implement code here
int index=0;
//CREATE WHILE LOOP TO READ DATA LINE BY LINE
while((line = file.readLine()) != null) {
//Print data to console line by line to ensure it reads data properly
System.out.println(line);
//we need to apply split method
String[] splits = line.split(","); //This will have total of 7 values
year[index] = Double.parseDouble(splits[0]);
month [index] = Double.parseDouble(splits[1]);
tmax [index] = Double.parseDouble(splits[2]);
tmin [index] = Double.parseDouble(splits[3]);
af [index] = Double.parseDouble(splits[4]);
rain [index] = Double.parseDouble(splits[5]);
sun [index] = Double.parseDouble(splits[6]);
sumYear += year[0];
sumMonth += month[1];
sumTmax += tmax[2];
sumTmin += tmin[3];
sumAF+= af[4];
sumRain += rain[5];
sumSun+= sun[6];
counter++;
index++;
} } catch (FileNotFoundException e1) {
e1.printStackTrace();
// TODO Auto-generated catch block
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//now print averages
double avgTmax = sumTmax/counter;
double avgTmin = sumTmin/counter;
double avgFrost = sumAF/counter;
double avgRain = sumRain/counter;
double avgSun = sumSun/counter;
System.out.println("Average: Maximum Temp: " + avgTmax);
System.out.println("Average: Minimum Temp: " + avgTmin);
System.out.println("Average: Rain: " + avgRain);
System.out.println("Average: Frost: " + avgFrost);
System.out.println("Average: Sun: " + avgSun);
}
}
答案 0 :(得分:1)
sumYear += year[0];
sumMonth += month[1];
sumTmax += tmax[2];
sumTmin += tmin[3];
sumAF += af[4];
sumRain += rain[5];
sumSun += sun[6];
必须是
sumYear += year[index];
sumMonth += month[index];
sumTmax += tmax[index];
sumTmin += tmin[index];
sumAF += af[index];
sumRain += rain[index];
sumSun += sun[index];
您已阅读由逗号分隔的值组成的行,将其拆分并将个别值(splits[0]
,splits[1]
.. splits[6]
)存储到相应的数组。要阅读它们,您需要使用您写过的相同index
。
修改强>
除非您需要存储实际值,否则您可以删除数组,并且可以简单地将运行总和计算为sumYear += Double.parseDouble(splits[0]);
(类似于所有)