From dd0577e05db5076d56f9b567b3a825afef2a7ece Mon Sep 17 00:00:00 2001 From: Burra Saiteja <99873259+burrasaiteja21@users.noreply.github.com> Date: Fri, 4 Oct 2024 19:18:08 +0530 Subject: [PATCH] Update getSecondHighestPriceByBrand.java Fixed the second highest price logic: Before, it only returned the first matching brand, but now it finds all matching footwear, sorts them by price, and returns the second highest one. Added sorting: I used a list to collect matching footwear, then sorted them by price from highest to lowest to get the correct result. These changes ensure that the program works as expected, especially when finding the second highest priced footwear for a brand. Signed-off-by: Burra Saiteja <99873259+burrasaiteja21@users.noreply.github.com> --- IPA2/footwearProgram.java | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/IPA2/footwearProgram.java b/IPA2/footwearProgram.java index 01ad07e..bef42b7 100644 --- a/IPA2/footwearProgram.java +++ b/IPA2/footwearProgram.java @@ -62,17 +62,28 @@ public static int getCountByType(Footwear[] ft, String t) } } - public static Footwear getSecondHighestPriceByBrand(Footwear[] ft, String name) + public static Footwear getSecondHighestPriceByBrand(Footwear[] ft, String name) { - for(int i =0; i matchingFootwear = new ArrayList<>(); + + // Collect footwears matching the brand name + for (Footwear footwear : ft) { + if (footwear.getName().equalsIgnoreCase(name)) { + matchingFootwear.add(footwear); + } + } + + // If there are less than two matching items, return null + if (matchingFootwear.size() < 2) { + return null; + } + + // Sort by price in descending order + matchingFootwear.sort((f1, f2) -> Integer.compare(f2.getPrice(), f1.getPrice())); + + // Return the second highest priced footwear + return matchingFootwear.get(1); + } } class Footwear