如何在java中添加相同的数组?

时间:2014-07-01 11:52:14

标签: java arrays sorting arraylist

这是我得到的代码。

    Scanner scanner = new Scanner(new File("file name"));
    ArrayList<Date> dateList = new ArrayList<Date>();
    ArrayList<Date> timeList = new ArrayList<Date>();
    ArrayList<String> consumptionList = new ArrayList<String>();
    DateFormat sdf = new SimpleDateFormat ("HH:mm");
    SimpleDateFormat dateInWeekday = new SimpleDateFormat ("MM/dd/yy");

    while(scanner.hasNextLine()){

        //read the line
        String currentLine = scanner.nextLine(); 
        String[] tokens = currentLine.split(",");

        //string of each value
        String date = tokens [0];
        String time = tokens [1];
        String consumption = tokens [2];

        //convert Str time to date format
        Date timeDateFormat = sdf.parse(time);
        timeList.add(timeDateFormat);
        consumptionList.add(consumption);
        dateList.add(dateInWeekday.parse(date));
    }

    scanner.close();



    double dayTotal = 0;
    int count = 0;

    for(int i = 0; i < dateList.size(); i++){

        Calendar c = Calendar.getInstance();
        c.setTime(dateList.get(i));
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

        if ((dayOfWeek == 1) || (dayOfWeek == 7)){

            dayTotal +=  Double.parseDouble(consumptionList.get(i));
            count ++;
            }       
    }
}

}

所以,我希望结果是,例如: 1/10/14 342 Kwh 1/11/14 292 Kwh 我的数据是每15分钟消耗一次,所以我想要每天消费总量

3 个答案:

答案 0 :(得分:0)

当然,Map<SomeType, Integer>使用SomeType类型abc。然后遍历你的数组(它看起来不像你的例子btw,但没关系)并添加计数。

答案 1 :(得分:0)

我会创建一个新的地图,其中包含字母和值作为累计和的值。然后,您可以迭代所有数组,查看映射中的键是否已存在,并将数组的值添加到映射值的前一个总和。 这将为您提供一个包含所有不同数组值之和的映射。

答案 2 :(得分:-1)

//assign the arrays as
a=(4,5,53);b=(1,55,6); c=(1,2);
double SumA=0;
double SumB=0;
double SumC=0;
//Then find the sum of elements in each array. 
//To get the sum of elements in each array use the for loop
 for(int i=0;i<a.size();i++){
     SumA = SumA + a.get(i);}
 for(int i=0;i<a.size();i++){
     SumB = SumB + b.get(i);}
 for(int i=0;i<a.size();i++){
     SumC = SumC + c.get(i);}

//The generate the final results as
[a,SumA] [b,SumB] [c,SumC]