数组,检查java中的最小,最大和平均值

时间:2013-04-12 21:40:37

标签: java arrays methods average

我在让我的方法工作方面遇到一些麻烦,我相信我在主要方法中做错了一些事情来调用其他方法。我不确定我是否需要if,while或for语句。任何人都可以帮忙,我真的很感激。这是我的计划......

  public static void main(String[] args) throws IOException {
    Scanner kb = new Scanner(System.in);
    final int MAX = 100;
    int [] myarray = new int [MAX];
    int fillsize, total = 0, num;
    int smallest = 0, largest = 0;
    fillsize = fillarray (myarray, MAX);
    printarray (myarray, fillsize);

    num = kb.nextInt(); 
    int small = num;
    int large = num;
    total = Average(total, num);
    if(smallest (num, smallest))
    {
      small = num;
    }
    if(largest(num, largest))
    {
       large = num;      
    }
    System.out.println("The smallest value is: " + smallest);
    System.out.println("The largest value is: " + largest);
    System.out.println("The average is: " + total);

    prw.close();
}

public static int fillarray (int[] num, int MYMAX){
    Random gen = new Random();
    int retval = 0;
    int randomnum;
    for(int count = 0; count <= 30; count++){
        randomnum = gen.nextInt(150);
        num [count] = randomnum;
        System.out.println(randomnum);
        retval++;   
    }
    System.out.println("The return value is: " + retval);
    return (retval);
}
public static void printarray (int[] num, int fillsize){
    for (int counts = 0; counts < fillsize; counts++){
        System.out.println("For the position ["+counts+"] the value is " + num[counts]);
    }
    return;
}
public static boolean smallest (int num1, int num2){
    boolean returnValue;
    if (num2 < num1){
        returnValue = true;
    }
    else {
        returnValue = false;
    }
    return (returnValue);
}
public static boolean largest (int number1, int number2){
    boolean returnVal;
    if (number1 > number2){
        returnVal = true;
    }
    else{
        returnVal = false;
    }
    return (returnVal);
}
public static int Average (int avg, int sum){
    int retVal;
    retVal = avg + sum;
    return(retVal);
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我怀疑问题是你设置的最小值和最大值都是num,这会让你多余。

尝试将它们都设置为0。

此外,您还有不同的名称变量和方法。 (混淆)。