Need Java array help using scanner class to output an average and sort method

后端 未结 4 2119
一整个雨季
一整个雨季 2020-12-04 03:35

After several hours, I haven\'t made progress on making a method to output the average. I also need to make a sort class. Overall, the assignment needs.

Develop meth

相关标签:
4条回答
  • 2020-12-04 04:17

    To sort find min and max you can use TreeSet collection class. If you are using primitive type or a wrapper class, in this case no need to add any comparison logic. otherwise you need to implement comparator or comparable methods. Here is a example of TreeSet for min and max data http://www.programcreek.com/2009/02/a-simple-treeset-example/ . For calculating average i suggest you can use a local variable and for each time you add a number to TreeSet you can update the average. For eg when you add a new number p to current average value v, calculate latest average as v = (v*size + p)/++size;

    0 讨论(0)
  • 2020-12-04 04:20
    int sum = 0;
    for (int d : arg ) sum += d;
    double average = 1.0d * sum / arg .length;
    

    this will help you to find average...

    0 讨论(0)
  • 2020-12-04 04:25

    Calculate the average like this:

    int sum = 0;
    double avg = 0;
    for (int i=0;i<array.length; i++){
       sum+=array[i];
    }
    avg = sum/array.length;
    
    0 讨论(0)
  • 2020-12-04 04:33

    In Java 8+ you could use IntStream and IntSummaryStatistics like

    int[] arr = { 3, 1, 2 };
    IntSummaryStatistics stats = IntStream.of(arr).summaryStatistics();
    System.out.printf("Min: %d, Max: %d, Average: %.2f%n", //
            stats.getMin(), stats.getMax(), stats.getAverage());
    IntStream.of(arr).sorted().forEach(System.out::println);
    
    0 讨论(0)
提交回复
热议问题