简体   繁体   中英

Store data from an array for later comparison

I have a program where a user enters 4 numbers. Once all numbers are entered the user is given the average, lowest, and highest value out of the four values. If the user continues the program it asks for 4 more values and again gives the average, lowest, and highest value out of those four values. (So on and so on...)

However, I can't seem to figure out how to compare the array results given to output the lowest lowest value, highest highest value, and average from all the results given out of all the results from each 4 digit array.

Please let me know if I need to explain some more.

*The code is not complete

package example;

import java.util.*;

public class Example {

double highestValue;
double lowestValue;
public static void main(String[] args) {

System.out.println("Hello (Enter each digit when prompted)");
System.out.println();

Scanner input = new Scanner(System.in);

String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
    // Calls inputDigit and stores array in array storage variable
    double[] array = inputDigit(input, "Enter a number: ");

    displayFirst(array);            
    highestChecker(array);

    System.out.println();

    yesOrNo = askToContinue(input);
    System.out.println();

    System.out.println();

        if (yesOrNo.equalsIgnoreCase("n")) {
            System.out.println("done!);
            displayHighest(array);
        }
    }
}

public static double[] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double[] array = new double[4];
    // For loop that stores each input by user
    for (int counter = 0; counter < array.length; counter++) {
        System.out.print(prompt);

        try {
            array[counter] = input.nextDouble();
            if (array[counter] <= 1000){
            } else if (array[counter] >= -100){
            } else {
                System.out.println("Error!\nEnter a number greater or equal to -100 and"
                        + "less or equal to 1000.");
            }
        } catch (InputMismatchException e){
            System.out.println("Error! Please enter a digit.");
            counter--; // This is designed to backup the counter so the correct variable can be input into the array
            input.next();
        }
    }
return array;
}

public static void displayFirst(double[] array){
    Arrays.sort(array);
    double highestValue = array[3];
    double lowestValue = array[0];
    double average = calculateAverage(array);
    System.out.println("RESULTS FOR CURRENT NUMBER CYCLE"
        + "\n--------------------------------"
        + "\nAverage Value - " + average
        + "\nHighest Value - " + highestValue
        + "\nLowest Value - " + lowestValue);
}

public static double[] highestChecker(double[] array){
    double[] arrayC = Arrays.copyOf(array, array.length);
    Arrays.sort(arrayC);
    double lowestChecked = arrayC[0];
    double highestChecked = arrayC[3];
    double highestAverage;
// Check lowest value

// Check highest value
return array;
}

public static void displayHighest(double[] array){
    Arrays.sort(array);
    double highestValue = array[0];
    double lowestValue = array[3];
    double average = calculateAverage(array);
    System.out.println("RESULTS FOR HIGHEST VALUE"
        + "\n-------------------------"
        + "\nHighest Average Value - " + average
        + "\nHighest Highest Value - " + highestValue
        + "\nHighest Lowest Value - " + lowestValue);
}

public static double calculateAverage(double[] array) {
    double sum = 0;
    double average;
       for (int i = 0; i < array.length; i++) {
            sum = sum + array[i];
}
average = (double)sum/array.length;
return average;
}

public static String askToContinue(Scanner input) {
    boolean loop = true;  
    String choice;
    System.out.print("Continue? (y/n): ");
do {
    choice = input.next();
    if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
        System.out.println();
        loop = false;
    } else {
        System.out.print("Please type 'Y' or 'N': ");
    }
} while (loop);
return choice;
}
}

Example output of what the program should do.

Enter a number: 2
Enter a number: 4
Enter a number: 6
Enter a number: 8
RESULTS FOR CURRENT NUMBER CYCLE
--------------------------------
Average Value - 5.0 // <-- This value should the highest average
Highest Value - 8.0
Lowest Value - 2.0

Continue? (y/n): y


Enter a number: 7
Enter a number: 5
Enter a number: 3
Enter a number: 1
RESULTS FOR CURRENT NUMBER CYCLE
--------------------------------
Average Value - 4.0
Highest Value - 7.0
Lowest Value - 1.0 // <-- This value should be the lowest, lowest value

Continue? (y/n): y


Enter a number: 9
Enter a number: 1
Enter a number: 4
Enter a number: 5
RESULTS FOR CURRENT NUMBER CYCLE
--------------------------------
Average Value - 4.75
Highest Value - 9.0 // <-- This value should be the highest, highest value
Lowest Value - 1.0 // <-- This value should be the lowest, lowest value

Continue? (y/n): n

You have exited the program. 
Thank you for your time.

This should be the final result.

RESULTS FOR HIGHEST VALUE
-------------------------
Highest Average Value - 5.0
Highest, Highest Value - 9.0
Lowest, Lowest Value - 1.0

To find the average you can make use of java-8

OptionalDouble average = Arrays.stream(array).average();

To find the lowest and highest elements we can sort it and use :

// sort the array (default by ascending)
Arrays.sort(array);
double lowest = array[0]; 
double highest = array[array.length - 1];

Since the array is sorted the first index should be the lowest element and the last the highest


EDIT :

To find the lowest and highest value overall you can define two static variables :

static double highestValueOverAll = Double.MIN_VALUE;
static double lowestValueOverAll = Double.MAX_VALUE;

Now in the highestChecker() (rename this probably)

public static double[] highestChecker(double[] array) {

        // ...

        if (lowestChecked < lowestValueOverAll)
            lowestValueOverAll = lowestChecked;

        if (highestChecked > highestValueOverAll)
            highestValueOverAll = highestChecked;

        // ...
}

Here we just do a simple swap if the current lowest/highest values are lesser/greater than the previous values. Once the while-loop completes you can print it out.

Note : Arrays are also objects so you don't need to sort them in every method.

What I understand by reading your problem description as well as comments that you are struggling with printing highestValue , lowestValue and highestAverage of overall calculations made so far.
In order to do that, first of all declare highestValue , lowestValue and highestAverage variables as public static double type at the beginning so as to access it from every part of the program. Then, after each iterations of calculations update these variables. So, you have to make following changes in your code:

  public class Example {
    public static double highestValue = Double.MIN_VALUE;
    public static double lowestValue = Double.MAX_VALUE;
    public static double highestAverage = Double.MIN_VALUE;

And, in highestChecker function add following changes:

double highestAverageChecked = calculateAverage(array);
highestAverage = Math.max(highestAverage, highestAverageChecked);
// Check lowest value
lowestValue = Math.min(lowestValue, lowestChecked);
// Check highest value
highestValue = Math.max(highestValue, highestChecked);

And, finally modify the displayHighest function by eliminating few lines of code as follows:

public static void displayHighest(double[] array) {
    System.out.println("RESULTS FOR HIGHEST VALUE"
            + "\n-------------------------" + "\nHighest Average Value - "
            + highestAverage + "\nHighest Highest Value - " + highestValue
            + "\nHighest Lowest Value - " + lowestValue);
}

Edit: added calculation for highestAverage as well.

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