简体   繁体   English

存储阵列中的数据以供以后比较

[英]Store data from an array for later comparison

I have a program where a user enters 4 numbers. 我有一个程序,用户输入4个数字。 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. 如果用户继续该程序,则它要求另外4个值,并再次给出这四个值中的平均值,最低值和最高值。 (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. 但是,我似乎无法弄清楚如何比较给出的数组结果,以输出每个4位数组的所有结果中给出的所有结果中的最低最低值,最高最高值和平均值。

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 要找到平均值,您可以使用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) 现在在highestChecker() (可能重命名)

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. while-loop完成后,您可以将其打印出来。

Note : Arrays are also objects so you don't need to sort them in every method. 注意:数组也是对象,因此您无需在每个方法中sort它们进行sort

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. 通过阅读您的问题描述以及您正在努力打印highestValue lowestValue highestAverage的总体计算的highestValuelowestValuehighestAverage的评论我理解了什么。
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. 为了做到这一点,首先将highestValuelowestValuehighestAverage变量声明为开头的public static double类型,以便从程序的每个部分访问它。 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: 并且,在highestChecker函数中添加以下更改:

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: 最后,通过消除几行代码来修改displayHighest函数,如下所示:

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. 编辑:还为highestAverage添加了计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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