简体   繁体   English

查找数组的最大最大值和平均值

[英]Finding the min max and average of an array

I need to find the min, max, and average of the balances. 我需要找到余额的最小值,最大值和平均值。 I have done this before using for loops, but never with a while loop. 我在使用for循环之前已经完成了这个,但是从来没有使用while循环。 Is there a way to pull the min max and average straight from the array without interfering with the while loop perhaps? 有没有办法从阵列中拉出最大最大值和平均值而不会干扰while循环?

10
Helene 1000
Jordan 755
Eve 2500
Ken 80
Andrew 999
David 1743
Amy 12
Sean 98
Patrick 7
Joy 14

where 10 is the number of accounts 其中10是账户数量

import java.util.*;
import java.io.*;
import java.util.Arrays;

public class bankaccountmain {

public static void main(String[] args) throws FileNotFoundException {
    Scanner inFile = null;
    try {
        inFile = new Scanner(new File("account.txt"));
        ;
    } catch (FileNotFoundException e) {
        System.out.println("File not found!");

        System.exit(0);
    }
    int count = 0;
    int accounts = inFile.nextInt();
    String[] names = new String[accounts];
    int[] balance = new int[accounts];
    while (inFile.hasNextInt()) {
        inFile.next();
        names[count] = inFile.next();
        inFile.nextInt();
        balance[count] = inFile.nextInt();
        count++;
    }
    System.out.println(Arrays.toString(names));
    System.out.println(Arrays.toString(balance));
    }
}

You are already pulling the values out of the file when you store them in balance[count] . 将值存储在balance[count]时,您已经将值拉出文件。 You can then use those values you have just read to do your calculations: 然后,您可以使用刚读过的值来进行计算:

    int min = Integer.MAX_VALUE;
    int max = 0;
    int total = 0;
    while (inFile.hasNext()) {
        names[count] = inFile.next();
        balance[count] = inFile.nextInt();  // balance[count] now is storing the value from the file

        if (balance[count] < min) {  // so I can use it like any other int
            min = balance[count];
        }
        if (balance[count] > max) {  // like this
            max = balance[count];
        }
        total += balance[count]; // and this
        count++;
    }
    double avg = (double)total/count;

The answer of azurefrog is correct and acceptable (+1). azurefrog的答案是正确和可接受的(+1)。

But I personally prefer to avoid "mixing" too much functionality. 但我个人更喜欢避免“混合”太多的功能。 In this case: I think that 在这种情况下:我认为

  • reading the values from a file and 从文件中读取值和
  • computing the min/max/avg 计算最小值/最大值/平均值

should be separate operations. 应该是单独的操作。

Computing the min/max/average of an int[] array is a very common operation. 计算int[]数组的最小值/最大值/平均值是一种非常常见的操作。 So common that it probably already has been implemented thousands of times (and it's a pity that this functionality was not available in the standard API before Java 8). 很常见,它可能已经实现了数千次(遗憾的是,在Java 8之前,标准API中没有提供此功能)。

However, if I had to implement something like this (and was not willing or allowed to use a sophisticated library solution like, for example, the SummaryStatistics of Apache Commons Math), I'd go for some utility methods: 但是,如果我必须实现类似的东西(并且不愿意或允许使用复杂的库解决方案,例如,Apache Commons Math的SummaryStatistics ),我会选择一些实用方法:

static int min(int array[]) 
{
    int result = Integer.MAX_VALUE;
    for (int a : array) result = Math.min(result, a);
    return result;
}

int max(int array[]) 
{
    int result = Integer.MIN_VALUE;
    for (int a : array) result = Math.max(result, a);
    return result;
}

static int sum(int array[]) 
{
    int result = 0;
    for (int a : array) result += a;
    return result;
}

static double average(int array[]) 
{
    return (double)sum(array)/array.length;
}

Another advantage (apart from the "purists" argument of "Separation Of Concerns") is that these methods are reusable. 另一个优点(除了“分离关注点”的“纯粹主义者”论点)是这些方法是可重复使用的。 You can put them into a IntArrays utility class, and whenever you need this functionality, you can just call these methods. 您可以将它们放入IntArrays实用程序类中,只要您需要此功能,就可以调用这些方法。

If you can already use Java 8, then it's even simpler, because exactly these operations now (finally!) are part of the standard API. 如果您已经可以使用Java 8,那么它甚至更简单,因为现在这些操作(最终!) 正是标准API的一部分。 They are offered in the IntStream class, that exactly has the min() , max() and average() methods that you need. 它们在IntStream类中提供,它具有您需要的min()max()average()方法。 There you could just write something like 在那里你可以写一些像

int min = IntStream.of(balance).min().getAsInt();
int max = IntStream.of(balance).max().getAsInt();
double average = IntStream.of(balance).average().getAsDouble();

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

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