Advertisement
Guest User

Untitled

a guest
Apr 27th, 2018
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. package demo;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.math.BigDecimal;
  7. import java.math.BigInteger;
  8. import java.math.RoundingMode;
  9. import java.nio.charset.StandardCharsets;
  10. import java.text.DecimalFormat;
  11. import java.util.ArrayList;
  12. import java.util.Arrays;
  13. import java.util.List;
  14. import java.util.stream.Collectors;
  15.  
  16. public class Pr01ArrayStatistics {
  17.  
  18.     public static void main(final String[] args) {
  19.  
  20.         try (final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
  21.             List<BigInteger> numbers = Arrays.stream(reader.readLine().trim().split("\\s+"))
  22.                     .map(BigInteger::new)
  23.                     .collect(Collectors.toCollection(ArrayList::new));
  24.  
  25.             BigInteger min = numbers.stream().min(BigInteger::compareTo).orElse(null);
  26.             BigInteger max = numbers.stream().max(BigInteger::compareTo).orElse(null);
  27.             BigInteger sum = numbers.stream().reduce(BigInteger.ZERO, BigInteger::add);
  28.             BigDecimal avr = new BigDecimal(sum).divide(new BigDecimal(numbers.size()), 15, RoundingMode.HALF_UP);
  29.  
  30.             System.out.printf("" +
  31.                     "Min = %d%n" +
  32.                     "Max = %d%n" +
  33.                     "Sum = %d%n" +
  34.                     "Average = %s%n", min, max, sum, doubleToStringCSharpLike(avr.doubleValue()));
  35.  
  36.  
  37.         } catch (IOException | NullPointerException e) {
  38.             e.printStackTrace();
  39.         }
  40.     }
  41.  
  42.     private static String doubleToStringCSharpLike(double value) {
  43.         int digits = 15;
  44.  
  45.         DecimalFormat df = new DecimalFormat("0.#");
  46.         df.setMaximumFractionDigits(digits);
  47.  
  48.         if (Math.abs(value) >= 1d) {
  49.             digits -= df.format(value).split("[.,]")[0].length();
  50.         }
  51.  
  52.         df.setMaximumFractionDigits(digits);
  53.         return df.format(value);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement