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

标签 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);
}

我做错了什么?

最佳答案

我怀疑问题是你将最小和最大都设置为 num 这使得你的 if 多余。

尝试将它们都设置为 0。

此外,您还拥有同名的变量和方法,但不建议这样做。 (令人困惑)。

关于java - java中数组,检查最小、最大和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981295/

相关文章:

php - 创建二维数组将数据移动到关键位置

java - 如何在构造函数中调用方法?

java - 是否可以使用java api在没有oauth的情况下在twitter上发推文

java - Java 中的泛型如何适用于以下程序?

java - 套接字编程中int数组的读写,java

java - 空数组和空数组有什么区别?

C++请求(blank)中的成员(blank),调用方法时为非类类型(blank)

java - 删除列表的一部分并在成功时返回 true 的方法的正确语法是什么?

java - 如何设置 Spring Security 以允许来自特定应用程序的 REST 调用?

java - 使用orientdb注解自动填充Pojo