在java中查找数组的最大值

时间:2014-09-03 00:33:57

标签: java arrays max

我在显示数组中的最大数字时遇到问题。这是我的代码。当我运行它时,它最多给我0.其余代码正常工作。

import java.util.Scanner;

public class Assignment2
{
    // method for the max
    public static int findMax(int[] numbers, int i)
    {
        int max; //max variable

        if(i > 0)
        {
            max = numbers[0];
        }
        else
        {
            max = 0;
        }

        for(int j = 1; j < i; j++)
        {
            if(numbers[i] > max)
                max = numbers[i];
        }
        return max;
    }

    // method to add positive numbers
    public static int computePositiveSum(int[] numbers, int i)
    {
        int total = 0;

        //check if positive number
        if ( i > 0)
        {
             int num = (numbers[i - 1] > 0) ? numbers[i -1]:0;
             total = num + computePositiveSum(numbers, i - 1);
             return total;
        }
        else
            return total;
    }


    // method to count negative numbers
    public static int countNegative(int[] numbers, int i)
    {
        // if the first input is the same as
        //length there are no negative numbers
        if(i == numbers.length)
        {
            return 0;
        }
        // initialize the number of negatives
        int sum = countNegative(numbers, i + 1);
        if(numbers[i] < 0)
        {
            sum++;
        }
        // return the number of negatives
        return sum;
    }


    public static void main (String[] args)
    {
        Scanner input = new Scanner(System.in);

        int [] numbers = new int[100];
        int count = 0;
        boolean quit = false;

        //add numbers to array
        for( int i= 0; i<numbers.length & quit == false; i++)
        {
            numbers[i]=input.nextInt();

            if(numbers[i] != 0)
            {
                count++;
            }
            else
            {
                quit = true;// exit by entering 0
            }
        }
        System.out.println("The maximum number is " + findMax(numbers, count));
        System.out.println("The sum of the positive numbers is " + computePositiveSum(numbers, count));
        System.out.println("The total number of negative numbers is " + countNegative(numbers, 0));
    }
}

2 个答案:

答案 0 :(得分:2)

在确定实际循环索引的最大值而不是i时,您使用的数字numbers(输入的数字数)作为j数组的索引。变化

if(numbers[i] > max)
    max = numbers[i];

if(numbers[j] > max)
    max = numbers[j];

为您的计数选择名称i(通常用作循环索引)令人困惑。将i重命名为count会更具可读性并且更少混淆。

答案 1 :(得分:0)

int a[] = { 1, 6, 7, 56, 5, 19, 26, 17 };

    int max = a[0];
    for (int i = 1; i < a.length; i++) {

        if (max < a[i]) {
            max = a[i];

        }
        else {
            max = max;
        }

    }
    System.out.println(max);
}

}