簡體   English   中英

查找數組的最大最大值和平均值

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

我需要找到余額的最小值,最大值和平均值。 我在使用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));
    }
}

將值存儲在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;

azurefrog的答案是正確和可接受的(+1)。

但我個人更喜歡避免“混合”太多的功能。 在這種情況下:我認為

  • 從文件中讀取值和
  • 計算最小值/最大值/平均值

應該是單獨的操作。

計算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;
}

另一個優點(除了“分離關注點”的“純粹主義者”論點)是這些方法是可重復使用的。 您可以將它們放入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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM