Advertisement
LoraOrliGeo

SumAdjacentEqualNumbers_Lists_Lab

Apr 8th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. package feb19_Lists_Lab;
  2.  
  3. import java.text.DecimalFormat;
  4. import java.util.Arrays;
  5. import java.util.List;
  6. import java.util.Scanner;
  7. import java.util.stream.Collectors;
  8.  
  9. public class SumAdjacentEqualNumbers {
  10.     public static void main(String[] args) {
  11.         @SuppressWarnings("resource")
  12.  
  13.         Scanner sc = new Scanner(System.in);
  14.  
  15.         List<Double> nums = Arrays.stream(sc.nextLine().split("\\s+")).map(Double::parseDouble)
  16.                 .collect(Collectors.toList());
  17.  
  18.         for (int i = 0; i < nums.size() - 1; i++) {
  19.             if (nums.get(i).equals(nums.get(i + 1))) {
  20.                 nums.set(i, (nums.get(i) + nums.get(i + 1)));
  21.                 nums.remove(nums.get(i + 1));
  22.                 i = -1;
  23.             }
  24.         }
  25.        
  26.         join(nums, " ");
  27.     }
  28.  
  29.     public static void join(List<Double> nums, String delimeter) {
  30.         DecimalFormat df = new DecimalFormat("#.###");
  31.         String output = "";
  32.         for (double num : nums) {
  33.             String formatted = df.format(num);
  34.             output += formatted + delimeter;
  35.         }
  36.         System.out.println(output);
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement