简体   繁体   中英

Finding MAX even and odd values in an array

I need to find the MAX even and odd values of a given array. In this case I need the console to print that the max even is 8 and the max odd is 11 This is revised from another question because of the cool down time for asking questions

import java.util.Scanner;
public class Question03 {

    public static int[] array;//The array to be used in the problem
    public static void main(String[] args) {
        int number;//Used for the stairs
        if(args == null || args.length == 0)
        {

            int[] tempArray ={2,4,6,8,11};//You may change these values to test 
            array = tempArray;
        }
        else
        {

        }

        //Write your solution here
        int evenMax = array[0];
        int oddMax = array[0];
        for (int x =1; x<array.length; x++){
            if(evenMax %2 == 0)
            {
                 if (evenMax<array[x])
                 {
                   
                 }
          }
          if(oddMax<array[x]){
            oddMax=array[x];
          }
        }

        System.out.println("The largest number is: " + evenMax + ". The smallest number is: " +oddMax);
        



You can use Streams from Java 8 along with Optional:

import java.util.Arrays;

public static void main(String[] args) {
    int[] array = {1,2,3};
    Arrays
        .stream(array)
        .filter(n -> n > 0)
        .average()
        .getAsDouble();
}

vide: DoubleStream and OptionalDouble

Just fixing your code, I added a variable to store the number of elements that should be used as divisor when calculating the average value. In this case total store the sum of all elements in the array.

int elements = array.length;
double total = 0;
for(int i=0; i<array.length; i++)
{
    if(array[i] < 0)
    {
        array[i] = 0;
    }
    if(array[i] == 0)
    {
        elements--;
    }
    total += array[i];
}
double average = total / elements;

System.out.println("the average was " +average);

PS As any algorithm there are many ways to solve this problem. But, here, my intent was to help you according to your line of thought.

How about something like this:

    double total = 0;
    int count = 0;
    for(int i=0; i<array.length; i++)
    {
        if(array[i] > 0)
        {
            total += array[i];
            ++count;
        }
    }
    double average = total / count;
    System.out.println("the average was " +average);

Or even:

    double total = 0;
    int count = 0;
    for(double value: array)
    {
        if(value > 0)
        {
            total += value;
            ++count;
        }
    }
    double average = total / count;
    System.out.println("the average was " +average);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM