如何计算列表的平均值?

vxf3dgd4  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(357)

这是我从服务器解析时的json:

{
      "main": [
        {
          "id": "12345"
        }
      ],
      "parameter": [
        {
          "temp": "30.00",
          "acc": "3.00",
          "moisture": "200.00",
          "battery": "98.00",
          "date": "2015-04-13",
          "time": "14:51:05"
        },
        {
          "temp": "32.00",
          "acc": "2.50",
          "moisture": "190.00",
          "battery": "80.00",
          "date": "2015-04-13",
          "time": "14:53:21"
        },
        {
          "temp": "27.00",
          "acc": "5.00",
          "moisture": "200.00",
          "battery": "60.00",
          "date": "2015-04-13",
          "time": "15:06:04"
        },
        {
          "temp": "21.00",
          "acc": "3.00",
          "moisture": "160.00",
          "battery": "60.00",
          "date": "2015-04-13",
          "time": "15:07:13"
        },
        {
          "temp": "30.00",
          "acc": "4.50",
          "moisture": "200.00",
          "battery": "65.00",
          "date": "2015-04-13",
          "time": "10:18:11"
        }
]
}

我有一种方法将时间从格式“hh:mm:ss”转换为“hh”。

public static int convertTime(String time) {

        Date formatTime = null;

        try {
            formatTime = new SimpleDateFormat("hh:mm:ss").parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        @SuppressWarnings("deprecation")
        int hour = formatTime.getHours();
        return hour;

    }

然后我要计算每次的平均温度。例如,当我转换为“hh”时,time=“14”有两个温度值,分别是“30和32”。如何计算平均温度?拜托,帮帮我。

rm5edbpk

rm5edbpk1#

JSONArray parameter=main.getJSONArray("parameter");
float[] avgTemp=new float[24];

//for 24 hours of the day
for(int i=0;i<24;i++){
     int occurence=0;
     float totalTemp=0;
     for(int j=0;j<parameter.size();j++){
          int time=convertTime(parameter.get(j).getString("time"));
          if(time==i){
               totalTemp+=Float.parseFloat(parameter.get(j).getString("temp"));
               occurence++;
              }
         avgTemp[i]=(totalTemp/occurence);
         }
    }

最后,你将得到数组中所有特定时间的平均温度

kx5bkwkv

kx5bkwkv2#

Something like this could be useful for you

Map<int, double[]> timeAndTemp = new HashMap<int,double[]>();    
String jSONData = *your json read as string*;
try (InputStream is = url.openStream();
JsonReader rdr = Json.createReader(new StringReader(jSONData)) {

    JsonObject obj = rdr.readObject();
    JsonArray results = obj.getJsonArray("parameters");
    for (JsonObject result : results.getValuesAs(JsonObject.class)) {
         int time = convertTime(result.getString("time"));
         double temp = double.parse(result.getString("temp"));
         if(!timeAndTemp.containsKey(time)){
             timeAndTemp.put(time, temp);
         } else {
             timeAndTemp.get(time).add(temp); 
         }
         timeAndTemp.put(time, temp);
    }
}

//then when you fill in all your data in the map you can easily iterate trough it and get all temperatures for a current time and sum them then divide on their number (the formula for an average number)
//here are some simple examples for using JsonReader and JsonWriter http://www.programmingforliving.com/2013/07/java-api-for-json-processing-jee7-p1.html
nszi6y05

nszi6y053#

@vishwaijt palankar,这是我的代码,请检查,当我运行logcat时,有更多的totaltemp和occurrence值。

public class Customadapter extends BaseAdapter {
        Context context;
        ArrayList<Parameter> parameterList;
        ArrayList<Parameter> tempArrayList = new ArrayList<Parameter>();
        long dateLong;
        String numhour;
        int count = 0;
        float sum = 0;
        HashMap<String, Float> tempMap;

        public Customadapter(Context context, int resource,
                ArrayList<Parameter> listParameters, long date) {
            super();
            this.context = context;
            this.dateLong = date;
            this.parameterList = getMyList(listParameters);
            Log.d("size", String.valueOf(parameterList.size()));
        }

        @SuppressWarnings("static-access")
        private ArrayList<Parameter> getMyList(ArrayList<Parameter> list) {
            for (Parameter parameter : list) {
                if (((new ConvertData()).convertDate((parameter.getDate()))) == dateLong) {

                    tempArrayList.add(parameter);
                }
            }

            return tempArrayList;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return parameterList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return parameterList.get(position);
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @SuppressLint("ViewHolder")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.listdatahistory, parent, false);

            float[] avgTemp = new float[24];

            for (int i = 0; i < 24; i++) {
                int occurenece = 0;
                float totaltemp = 0;
                for (int j = 0; j < parameterList.size(); j++) {
                    int time = ConvertData.convertTime(parameterList.get(j)
                            .getTime());
                    if (time == i) {
                        totaltemp += parameterList.get(j).getTemp();
                        occurenece++;
                    }
                    avgTemp[i] = (totaltemp / occurenece);
                    Log.d("temp", String.valueOf(totaltemp));
                    Log.d("occ", String.valueOf(occurenece));
                }

            }

            TextView temp = (TextView) view.findViewById(R.id.tempList);
            temp.setText("" + avgTemp);

            TextView bat = (TextView) view.findViewById(R.id.batList);
            bat.setText("" + parameterList.get(position).getDate());

            return view;
        }

    }

相关问题