We have to pass the array through a method that takes the highest, lowest, and average then have them print.
I'm having issues with getting the lowest value assigned to minNum.
Thank you!
public static void averageMaxMinMethod(double[] arrayOfDoubles){
double maxNum = 0;
double minNum = 0;
for(int i = 0; i < arrayOfDoubles.length; i ){
if(arrayOfDoubles[i] > maxNum)
maxNum = arrayOfDoubles[i];
if(arrayOfDoubles[i] < minNum)// <=== My poor attempt of getting the lowest value
minNum = arrayOfDoubles[i];
}
System.out.println("Highest given double is: " maxNum);
System.out.println("Lowest given double is: " minNum);
}
public static void main(String[] args) {
//1-3: Set up Scanner object to collect user's input on the size of array.
Scanner keyboard = new Scanner(System.in);
System.out.println("How many double numerical entries do you have?");
//4: Declare an array of size sizeOfArray
int sizeOfArray = keyboard.nextInt();
//Initialize array
double[] arrayOfDoubles;
arrayOfDoubles = new double[sizeOfArray];
for(int i = 0; i < sizeOfArray; i ){
//5: Use the Random number Class and walk over the array
Random randomNum = new Random();
arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
}
//6: Invoke SumMethod
sumMethod(arrayOfDoubles);
averageMaxMinMethod(arrayOfDoubles);
}
CodePudding user response:
double maxNum = 0;
double minNum = 0;
This only works if the maximum number is at least zero, and the minimum value is at most zero - otherwise, these values are not updated.
Instead, use the first element in the array, which is at least as large as the minimum, and at least as small as the maximum.
double maxNum = arrayOfDoubles[0];
double minNum = arrayOfDoubles[0];
Of course, you then don't need to compare these on the first loop iteration, so you can start the loop index at 1:
for(int i = 1; i < arrayOfDoubles.length; i ){
CodePudding user response:
Others have pointed out the mistake you made in your current implementation, however you also forgot to calculate the average. You don't actually have to write code to do that, Java includes DoubleSummaryStatistics
which can give you the max
, the min
, and the average
. Like,
public static void averageMaxMinMethod(double[] arrayOfDoubles) {
DoubleSummaryStatistics dss = DoubleStream.of(arrayOfDoubles).summaryStatistics();
System.out.println("Highest given double is: " dss.getMax());
System.out.println("Lowest given double is: " dss.getMin());
System.out.println("Average is: " dss.getAverage());
}
CodePudding user response:
If you need to max, min and average values you can use DoubleStream
and DoubleSummaryStatistics
:
double[] arrayOfDoubles = {5.1, 3.7, -2.9, 4.3, -11.2};
DoubleSummaryStatistics statistics = Arrays.stream(arrayOfDoubles).summaryStatistics();
System.out.println("Highest: " statistics.getMin());
System.out.println("Lowest: " statistics.getMax());
System.out.println("Average: " statistics.getAverage());
Output:
Highest: -11.2
Lowest: 5.1
Average: -0.2