添加方法时遇到问题

时间:2014-11-20 01:02:31

标签: java arrays methods

添加三个方法,一个将返回数组中的最大值(FindMax),一个将返回数组中的最小值(FindMIn),另一个将返回数组中值的平均值(FindAvg)

import java.util.Scanner;

public class methods {

    public static void main(String[] args) {

        int [] numbrs;
        numbrs = new int[25];
        int i = 0;
        System.out.println();
        populateArray(numbrs, numbrs.length);
        System.out.println("\n********** the array reversed is **********\n");
        for (i = numbrs.length - 1; i >= 0; i--)
        System.out.println(numbrs[i]);

        System.out.println("\n***** end of Array01.java *****");
      } // end of main method

/* ********************************************************
   Pre Condition: an array of n integers where n is given.

   Post Condition: an array populated with randomly
   generated integers in the range of 1 to limit
   specified by the user.
   ******************************************************** */

    public static void populateArray(int [] arry, int lm) {
        Scanner kBd;
        int lim = 0;
        kBd = new Scanner(System.in);
        System.out.print("Enter the upper limit of random numbers...");
        lim = kBd.nextInt();
        System.out.println();
        int x = 0;
        for(int i = 0; i < lm; i++) {
        arry[i] = getRandomInt(lim);
        System.out.println(arry[i]);
    }
    } // end of populateArray method

/* ********************************************************
   Pre Condition: an integer for the upper limit of the
   random number to generate.
   Post Condition: an integer in the range of 1 to limit
   ******************************************************** */

    public static int getRandomInt(int limit) {
        return (1 + (int)(Math.random() * limit));

    } // end of getRandomInt method

    public static int max(int highest) {

    } // end of class Array01

1 个答案:

答案 0 :(得分:1)

圣诞快乐。我今天心情愉快。这就是你如何计算出数组中最大的值:

public static int max(int[] array)
{
    int highest = array[0];
    for (int i = 1; i < array.length; i++)
    {
        if (array[i] > highest)
        {
            highest = array[i];
        }
    }
    return highest;
}

基本上,假设第一个存储值是最大值并将其与下一个值进行比较。如果下一个值最大,则分配给highest变量。继续遍历数组,直到检查每个值。一次通过,你就完成了。