Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/190.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何计算列表的平均值?_Java_Android_Json - Fatal编程技术网

Java 如何计算列表的平均值?

Java 如何计算列表的平均值?,java,android,json,Java,Android,Json,这是我从服务器解析时的json: { "main": [ { "id": "12345" } ], "parameter": [ { "temp": "30.00", "acc": "3.00", "moisture": "200.00", "battery": "98.00", "date

这是我从服务器解析时的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”的方法

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

这样的东西可能对你有用
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 
Map timeAndTemp=new HashMap(); String jSONData=*您的json读取为String*; try(InputStream=url.openStream(); JsonReader rdr=Json.createReader(新的StringReader(jSONData)){ JsonObject obj=rdr.readObject(); JsonArray results=obj.getJsonArray(“参数”); for(JsonObject结果:results.getValuesAs(JsonObject.class)){ int time=convertTime(result.getString(“time”); double temp=double.parse(result.getString(“temp”); 如果(!timeAndTemp.containsKey(time)){ 时间和温度输入(时间、温度); }否则{ timeAndTemp.get(time).add(temp); } 时间和温度输入(时间、温度); } } //然后,当你在地图中填写所有数据时,你可以很容易地通过它进行迭代,得到当前时间的所有温度,并将它们相加,然后除以它们的数字(平均数的公式) //下面是一些使用JsonReader和JsonWriter的简单示例http://www.programmingforliving.com/2013/07/java-api-for-json-processing-jee7-p1.html
JSONArray参数=main.getJSONArray(“参数”);
浮动[]avgTemp=新浮动[24];
//一天24小时

对于(int i=0;i@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;
        }

    }
公共类Customadapter扩展了BaseAdapter{
语境;
ArrayList参数列表;
ArrayList tempArrayList=新建ArrayList();
长期的;
弦numhour;
整数计数=0;
浮点数和=0;
HashMap-tempMap;
公共Customadapter(上下文、int资源、,
ArrayList列表参数,长日期){
超级();
this.context=上下文;
this.dateLong=日期;
this.parameterList=getMyList(listParameters);
Log.d(“size”,String.valueOf(parameterList.size());
}
@抑制警告(“静态访问”)
私有ArrayList getMyList(ArrayList列表){
用于(参数:列表){
if(((new ConvertData()).convertDate((parameter.getDate()))==dateLong){
tempArrayList.add(参数);
}
}
返回临时列表;
}
@凌驾
public int getCount(){
//TODO自动生成的方法存根
返回参数list.size();
}
@凌驾
公共对象getItem(int位置){
//TODO自动生成的方法存根
返回参数list.get(位置);
}
@凌驾
公共长getItemId(int arg0){
//TODO自动生成的方法存根
返回arg0;
}
@SuppressLint(“视图持有者”)
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
LayoutFlater充气器=(LayoutFlater)上下文
.getSystemService(上下文布局\充气机\服务);
视图=充气机。充气(R.layout.listdatahistory,父项,false);
浮动[]avgTemp=新浮动[24];
对于(int i=0;i<24;i++){
int=0;
浮动总温度=0;
对于(int j=0;j
只需选择与您的时间范围相匹配的值,将这些值相加并除以所选元素的数量即可。例如,您有两个临时值30和32,然后
avarageTemp=(30+32)/2、 
我认为OP想知道如何通过JSON和他的方法达到这一目的。这只是一个例子,如果数据很大,那么你应该怎么做?@sebhaub,Batuhan最好的方法是拥有一个哈希图,24个键表示一天24小时,然后循环JSON数据,使用你编写的实用方法,并开始按如下方式计算和存储值:你在循环中读取了ahed。请检查下面我的答案,请@vishwajit在最后做一件事打印数组中计算的所有值并检查它们,而不是打印温度和事件打印时间和该时间的平均温度,如下面的Log.d(“time”,String.valueOf(time));Log.d(“平均温度”,String.valueOf(avgTemp[i]);请问这行temp.setText(“+avgTemp”)是什么意思array@Vishwajittotaltemp+=parameterList.get(j).getTemp()不正确。它计算list的所有值
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);
         }
    }
 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;
        }

    }