【问题标题】:How can I add the same array together in java?如何在java中将相同的数组添加在一起?
【发布时间】:2014-08-21 23:24:04
【问题描述】:

这是我得到的代码。

    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 ++;
            }       
    }
}

}

所以,我希望结果是,例如: 2014 年 1 月 10 日 342 千瓦时 2014 年 1 月 11 日 292 千瓦时 我的数据是每 15 分钟的消耗量,所以我想要每天的总消耗量

【问题讨论】:

  • 到目前为止您尝试过什么?发布一些代码,以便其他人可以帮助您。
  • 那是一个数组吗?因为它看起来像多个数组。贴一些代码,因为很难理解你需要什么。
  • 这,小伙子,不是数组。
  • 请添加包含在文件中的示例数据。

标签: java arrays sorting arraylist


【解决方案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]

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      当然,使用Map&lt;SomeType, Integer&gt;SomeTypeabc 的类型。然后遍历您的数组(顺便说一句,它看起来不像您的示例中的一个,但没关系)并添加计数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-19
        • 1970-01-01
        • 1970-01-01
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多