[英]Finding MAX even and odd values in an array
I need to find the MAX even and odd values of a given array.我需要找到给定数组的 MAX 偶数值和奇数值。 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
在这种情况下,我需要控制台打印最大偶数为 8,最大奇数为 11 这是从另一个问题修订的,因为提问的冷却时间
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:您可以将 Java 8 中的 Streams 与 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视频: DoubleStream和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.在这种情况下,
total
存储数组中所有元素的总和。
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. PS 作为任何算法,有很多方法可以解决这个问题。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.