Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package L12ObjectsAndClassesExercise.P06VehicleCatalogue;
- import javax.swing.plaf.synth.SynthOptionPaneUI;
- import java.util.*;
- import java.util.stream.Collectors;
- public class Main {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- String command = scan.nextLine();
- List<Vehicle> vehicles = new ArrayList<>();
- while (!"End".equals(command)) {
- vehicles.add(new Vehicle(command));
- command = scan.nextLine();
- }
- command = scan.nextLine();
- while (!"Close the Catalogue".equals(command)) {
- String model = command;
- vehicles.stream().filter(x->x.getModel().equals(model))
- .forEach(x-> System.out.println(x));
- command = scan.nextLine();
- }
- System.out.printf("Cars have average horsepower of: %.2f.\n"
- , calculateAverageHorsePower(vehicles, "car"));
- System.out.printf("Trucks have average horsepower of: %.2f.\n"
- , calculateAverageHorsePower(vehicles, "truck"));
- }
- private static double calculateAverageHorsePower(List<Vehicle> vehicles, String type) {
- var vehiclesHorsePowers = vehicles.stream().filter(x -> x.getType().equals(type)).mapToInt(x -> x.getHorsePowers()).toArray();
- int sum = Arrays.stream(vehiclesHorsePowers).sum();
- return (vehiclesHorsePowers.length == 0) ? 0: sum / (double) vehiclesHorsePowers.length;
- }
- public static class Vehicle {
- private String type;
- private String model;
- private String color;
- private int horsePowers;
- public Vehicle(String str) {
- String[] input = str.split(" ");
- this.type = input[0];
- this.model = input[1];
- this.color = input[2];
- this.horsePowers = Integer.parseInt(input[3]);
- }
- public String getType() {
- return type;
- }
- public int getHorsePowers() {
- return horsePowers;
- }
- public String getModel() {
- return model;
- }
- @Override
- public String toString(){
- return String.format("Type: %s\n" +
- "Model: %s\n" +
- "Color: %s\n" +
- "Horsepower: %d", this.type.toUpperCase(Locale.ROOT).charAt(0) + this.type.substring(1), this.model, this.color, this.horsePowers);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment