如何在Java中找到二维数组中的min和max

时间:2018-04-04 17:25:27

标签: java arrays multidimensional-array max min

public class Average {

    static Integer[][] myDouble = new Integer[10][12];
    static int x = 0, y = 0;
    static int strDouble;

    public Average() {
        try {
            BufferedReader in = new BufferedReader(new FileReader("StudentIdAverage.txt"));
            String line;
            while ((line = in.readLine()) != null) {
                String[] values = line.split("\\s+");

                for (String str : values) {
                    strDouble = Integer.parseInt(str);
                    myDouble[x][y] = strDouble;
                    y = y + 1;
                }
                x = x + 1;
                y = 0;
            }
            in.close();
        } catch (IOException ioException) {
        }
    }

    public static void main(String[] args) {

        Average arr = new Average();


        for (int k = 0; k < myDouble.length; ++k) {
            int count = 0; // count the values used to calculate sum
            int sum = 0;
            int average = 0;

            for (int j = 0; j < myDouble[k].length; ++j) {

                if (myDouble[k][j] == null) //skip the null values
                {

                    continue;
                }


                sum += myDouble[k][j];
                count++;

                System.out.print(Average.myDouble[k][j] + " ");

            }

            average = (sum / count); //use count instead of lenght

            System.out.println(" ");


        }

    }
}


/*
input txt file

45 72 90 50 67 63 81 71 55 56 80 74/n 55 54 79 72 75 68/n 51 88 79 72/n 98 52 52 53 50 92 67 99 92 50 61 91/n 94 48 53 92 97/n 97 69 77 74 68 54 87 74 54 83 58 69/n 75 49 87 61 66 53 79 48 96 60/n 58 71 51 73 53 75 93 81 45 69 78 65/n 50 88 78 81 99 61 97 70 87 80 69/n 91 89 97 80 93 82 92 49 52 69 96 61
*/

1 个答案:

答案 0 :(得分:2)

让java流为您做繁重的工作:

IntSummaryStatistics stats = Arrays.stream(myDouble)
                                   .flatMap(Arrays::stream)
                                   .filter(Objects::nonNull)
                                   .mapToInt(Integer::intValue)
                                   .summaryStatistics();

int min = stats.getMin();
int max = stats.getMax();
double avg = stats.getAverage();