Guest User

06_VehicleCatalogue

a guest
Aug 6th, 2021
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. package L12ObjectsAndClassesExercise.P06VehicleCatalogue;
  2.  
  3. import javax.swing.plaf.synth.SynthOptionPaneUI;
  4. import java.util.*;
  5. import java.util.stream.Collectors;
  6.  
  7. public class Main {
  8. public static void main(String[] args) {
  9. Scanner scan = new Scanner(System.in);
  10. String command = scan.nextLine();
  11.  
  12. List<Vehicle> vehicles = new ArrayList<>();
  13.  
  14. while (!"End".equals(command)) {
  15. vehicles.add(new Vehicle(command));
  16. command = scan.nextLine();
  17. }
  18.  
  19. command = scan.nextLine();
  20. while (!"Close the Catalogue".equals(command)) {
  21. String model = command;
  22. vehicles.stream().filter(x->x.getModel().equals(model))
  23. .forEach(x-> System.out.println(x));
  24.  
  25. command = scan.nextLine();
  26. }
  27.  
  28. System.out.printf("Cars have average horsepower of: %.2f.\n"
  29. , calculateAverageHorsePower(vehicles, "car"));
  30. System.out.printf("Trucks have average horsepower of: %.2f.\n"
  31. , calculateAverageHorsePower(vehicles, "truck"));
  32.  
  33. }
  34.  
  35. private static double calculateAverageHorsePower(List<Vehicle> vehicles, String type) {
  36. var vehiclesHorsePowers = vehicles.stream().filter(x -> x.getType().equals(type)).mapToInt(x -> x.getHorsePowers()).toArray();
  37. int sum = Arrays.stream(vehiclesHorsePowers).sum();
  38. return (vehiclesHorsePowers.length == 0) ? 0: sum / (double) vehiclesHorsePowers.length;
  39. }
  40.  
  41. public static class Vehicle {
  42. private String type;
  43. private String model;
  44. private String color;
  45. private int horsePowers;
  46.  
  47. public Vehicle(String str) {
  48. String[] input = str.split(" ");
  49. this.type = input[0];
  50. this.model = input[1];
  51. this.color = input[2];
  52. this.horsePowers = Integer.parseInt(input[3]);
  53. }
  54.  
  55. public String getType() {
  56. return type;
  57. }
  58.  
  59. public int getHorsePowers() {
  60. return horsePowers;
  61. }
  62.  
  63. public String getModel() {
  64. return model;
  65. }
  66.  
  67. @Override
  68. public String toString(){
  69. return String.format("Type: %s\n" +
  70. "Model: %s\n" +
  71. "Color: %s\n" +
  72. "Horsepower: %d", this.type.toUpperCase(Locale.ROOT).charAt(0) + this.type.substring(1), this.model, this.color, this.horsePowers);
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment