RGAlex

Main

Feb 21st, 2021
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. package Exercise.O6Exercise;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Scanner;
  6. import java.util.stream.Collectors;
  7.  
  8. public class Main {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.         String input = scanner.nextLine();
  12.  
  13.         List<Vehicle> vehicles = new ArrayList<>();
  14.         while (!"End".equals(input)) {
  15.  
  16.             String[] command = input.split("\\s+");
  17.  
  18.             String type = command[0];
  19.             String model = command[1];
  20.             String color = command[2];
  21.             int horsePower = Integer.parseInt(command[3]);
  22.  
  23.             Vehicle vehicle = new Vehicle();
  24.  
  25.             vehicle.setType(type);
  26.             vehicle.setModel(model);
  27.             vehicle.setColor(color);
  28.             vehicle.setHorsePower(horsePower);
  29.             vehicles.add(vehicle);
  30.  
  31.             input = scanner.nextLine();
  32.         }
  33.  
  34.         String model = "";
  35.         while (!"Close the Catalogue".equals(model = scanner.nextLine())) {
  36.             String finalModel = model;
  37.             vehicles
  38.                     .stream()
  39.                     .filter(v -> v.getModel().equals(finalModel))
  40.                     .forEach(System.out::println);
  41.  
  42.         }
  43.         System.out.println(String.format("Cars have average horsepower of: %.2f.", average(vehicles.stream()
  44.                 .filter(v -> v.getType().equals("car"))
  45.                 .collect(Collectors.toList()))));
  46.  
  47.         System.out.println(String.format("Trucks have average horsepower of: %.2f.", average(vehicles.stream()
  48.                 .filter(v -> v.getType().equals("truck"))
  49.                 .collect(Collectors.toList()))));
  50.  
  51.     }
  52.  
  53.     private static double average(List<Vehicle> vehicles) {
  54.         if (vehicles.size() == 0) {
  55.             return 0.0;
  56.         }
  57.         double sum = 0;
  58.  
  59.         for (Vehicle vehicle : vehicles) {
  60.             sum += vehicle.getHorsePower();
  61.         }
  62.         return sum / vehicles.size();
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment