如何在阵列中获得多模式?

时间:2013-09-17 11:14:50

标签: java android math

嗨我正在制作一个计算平均值,中位数和模式的程序......平均值和中位数的计算已经完成,但我在计算模式时遇到了问题。该程序仅显示最低模式。如果有多种模式怎么办?请帮帮我。谢谢:)

    final AutoCompleteTextView inputValues = (AutoCompleteTextView) findViewById(R.id.txt_input);

    final TextView txtTotalNum = (TextView) findViewById(R.id.txt_totalNumber);
    final TextView txtMean = (TextView) findViewById(R.id.txt_mean);
    final TextView txtMedian = (TextView) findViewById(R.id.txt_median);
    final TextView txtMode = (TextView) findViewById(R.id.txt_mode);

    Button btnCalculate = (Button) findViewById(R.id.btncalculate);
    btnCalculate.setOnClickListener(new OnClickListener(){

        public void onClick(View arg0){


            //get the total number of values entered
            String []values = ( inputValues.getText().toString().split(","));
            int[] sortedValues = new int[values.length];
            txtTotalNum.setText(Integer.toString(values.length));

            //compute for the mean
            double meanResult=0;
            double totalValues=0;
            int e=0;
            for(e=0;e<values.length;e++){
                totalValues += Double.parseDouble(values[e]);
                sortedValues[e]= Integer.parseInt(values[e]);
            }
            meanResult= totalValues/values.length;
            txtMean.setText(Double.toString(meanResult));

            //compute for the median
            Arrays.sort(sortedValues);

            int elementNumber=0;            
            if (sortedValues.length %2==0)
            {
                elementNumber= sortedValues.length/2;
                txtMedian.setText(Double.toString((sortedValues[elementNumber-1] +sortedValues[elementNumber] )/2 ));
            }
            else
            {
                elementNumber= (sortedValues.length + 1)/2;
                txtMedian.setText(Integer.toString(sortedValues[elementNumber-1]));
            }

            //compute for the mode

            int maxValue = 0;
            int maxCount=0;

            for (int i = 0; i < sortedValues.length; ++i) {
              int count = 0;
                for (int j = 0; j < sortedValues.length; ++j) {
                  if (sortedValues[j] == sortedValues[i]) ++count;
                   }
            if (count > maxCount) {
            maxCount = count;
            maxValue = sortedValues[i];
            }

            txtMode.setText(Integer.toString(maxValue));


        }

        }

    });

1 个答案:

答案 0 :(得分:0)

使用ArrayList而不是数组,这样你也可以保存双峰值..希望有所帮助

ArrayList<Integer> maxValues = null;
int maxCount=0;

for (int i = 0; i < sortedValues.length; ++i) {

  int count = 0;
  for (int j = 0; j < sortedValues.length; ++j) {

    if (sortedValues[j] == sortedValues[i]) {
      ++count;
    }
  }

  if (count == maxCount) {
    maxValues.add(sortedValues[i]);
  }

  if (count > maxCount) {
    maxCount = count;
    maxValues.clear();
    maxValues.add(sortedValues[i]);
  }
}