Skip to content

issue in the code of IPA-2 #15

@jeevan340

Description

@jeevan340

I noticed an issue with the code provided for the IPA-2 question. Upon testing it with the sample input and output, I found that the logic implemented is incorrect. The problem specifically asks for the second highest price, but the code you shared is returning the lowest price instead.

I’ve implemented a corrected version of the code myself and would like to share it with you for verification. Kindly review it and consider updating the code in your repository accordingly.

Thank you!
Here's the Code:

import java.util.Arrays;
import java.util.Scanner;

public class footWearProgramm{
public static void main(String[] args){
Footwear[] foot=new Footwear[5];
Scanner sc=new Scanner(System.in);
for(int i=0;i<5;i++){
int a=sc.nextInt(); sc.nextLine();
String b=sc.nextLine();
String c=sc.nextLine();
int d=sc.nextInt();sc.nextLine();

  foot[i]=new Footwear(a,b,c,d);
}
String s1=sc.nextLine();
String s2=sc.nextLine();

sc.close();

int ans1=getCountByType(foot,s1);
if(ans1>0){
  System.out.println(ans1);
}
else{
  System.out.println("Footwear Not Available");
}
Footwear ans2=getSecondHighestPriceByBrand(foot,s2);
if(ans2!=null){
  System.out.println(ans2.getFootwearId());
  System.out.println(ans2.getFootwearName());
  System.out.println(ans2.getPrice());
} 
else{
  System.out.println("Brand not available");
}

}
public static int getCountByType(Footwear[] foot,String s1){
int count=0;
for(int i=0;i<foot.length;i++){
if(foot[i].getFootwearType().equalsIgnoreCase(s1)){
count++;
}
}
return count;
}
public static Footwear getSecondHighestPriceByBrand(Footwear[] foot,String s2){
Footwear[] obj=new Footwear[0];
int c=0;
for(int i=0;i<foot.length;i++){
if(foot[i].getFootwearName().equalsIgnoreCase(s2)){
obj=Arrays.copyOf(obj, obj.length+1);
obj[obj.length-1]=foot[i];
c++;
}
}
Footwear val=null;
if(obj.length>2){
for(int i=0;i<obj.length;i++){
for(int j=i+1;j<obj.length;j++){
if(obj[i].getPrice()>obj[j].getPrice()){
val=obj[i];
obj[i]=obj[j];
obj[j]=val;
}
}
}
return obj[obj.length-2];
}
if(c>0){
return obj[obj.length-1];
}

else
return null;

}
}
class Footwear{
private int footwearId,price;
private String footwearName,footwearType;

public int getFootwearId(){
return footwearId;
}
public int getPrice(){
return price;
}
public String getFootwearName(){
return footwearName;
}
public String getFootwearType(){
return footwearType;
}

public Footwear(int footwearId,String footwearName,String footwearType,int price){
this.footwearId=footwearId;
this.footwearName=footwearName;
this.footwearType=footwearType;
this.price=price;
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions