Java构造函数和返回

时间:2015-12-06 13:49:30

标签: java

我在完成作业时遇到了麻烦;这个问题要求我:

  1. 编写一个程序,计算并打印整数列表x1到xn的均值和标准差
  2. 假设输入值不超过50,最大可能值为100。
  3. 创建一个驱动程序类,该类随机生成小于或等于最大值100的值。
  4. 我为第一部分编写了代码,用于计算平均值和标准差:

        public class Statistics
        {
    
    
        public float getMean(int[] numbers){
    
            int count = 0;
            float output = 0;
               for (int i=0; i<numbers.length; i++)
               { 
                   count = count + numbers[i];
               }
               output = ((float)count/numbers.length);
               return output;
        }
    
    
        public float standardDeviation(int[] numbers, int count)
    
        {
    
                        float mean = getMean(numbers);
                        float output2 = 0;
    
                        float totalSdvMean = 0.0f;
    
                        for (int i=0 ; i<numbers.length; i++)
                        { 
    
                            float dev1 = numbers[i] - totalSdvMean;
                            dev1 = dev1 * dev1;
                            totalSdvMean += dev1;
                        }
                          output2 =(float)Math.sqrt(totalSdvMean/numbers.length);
                          return output2;
            }
    
        }
    

    其次这是我的司机班:

        import java.util.Random;
    
        public class StatisticsDriver
        {
        private static final int MAX_COUNT = 50, MAX_VALUE = 100;
    
    
        public static void main(String args[]){
    
              int[] numbers = new int[MAX_COUNT];
    
              Random generator = new Random();
    
              for (int i = 0; i < MAX_COUNT; i++)
              {
                  numbers[i] = generator.nextInt(MAX_VALUE);
              }
    
              getMean mean = new getMean(numbers);
              standardDeviation sdv = new standardDeviation(numbers);
    
              float mean = getMean(numbers);
              System.out.println(mean);
    
             float sdv = standardDeviation(numbers);
            System.out.println(sdv);
           }
        }
    

    我似乎无法获得返回值而且我完全被难倒了。我认为我的构造函数中有一个错误,但我不知道它是什么。任何帮助将不胜感激。

    谢谢!

1 个答案:

答案 0 :(得分:2)

getMean mean = new getMean(numbers);

getMean是一个方法,而不是一个类,所以你必须创建它所属的类的实例才能调用该方法:

Statistics stat = new Statistics ();
float mean = stat.getMean(numbers);

同样适用于standardDeviation

float sdv = stat.standardDeviation(numbers);