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

时间:2014-04-25 21:17:45

标签: java arrays max average min

我需要找到余额的最小值,最大值和平均值。我在使用for循环之前已经完成了这个,但是从来没有使用while循环。有没有办法从阵列中拉出最大最大值和平均值而不会干扰while循环呢?

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

其中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));
    }
}

2 个答案:

答案 0 :(得分:2)

当您将值存储在balance[count]中时,您已经将值从文件中提取出来。然后,您可以使用刚刚读过的值进行计算:

    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;

答案 1 :(得分:0)

azurefrog的答案是正确且可接受的(+1)。

但我个人更愿意避免&#34;混合&#34;功能太多了。在这种情况下:我认为

  • 从文件中读取值
  • 计算min / max / avg

应该是单独的操作。

计算int[]数组的最小值/最大值/平均值是一种非常常见的操作。如此常见,它可能已经实现了数千次(并且遗憾的是,在Java 8之前,标准API中没有提供此功能)。

但是,如果我必须实现类似的东西(并且不愿意或允许使用复杂的库解决方案,例如,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;
}

另一个优点(除了&#34;纯粹主义者&#34;&#34;分离关注&#34;的论点)是这些方法是可重复使用的。您可以将它们放入IntArrays实用程序类中,只要您需要此功能,就可以调用这些方法。

如果您已经可以使用Java 8,那么它甚至更简单,因为现在(最终!)的这些操作正是标准API的一部分。它们在IntStream类中提供,它完全具有您需要的min()max()average()方法。在那里你可以写一些类似

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