0% found this document useful (0 votes)
8 views6 pages

Java Gift Price Comparison Program

This Java code defines a Gift class and methods to find the lowest priced gift by a given brand and the third highest priced gift. It takes gift details as input, stores them in an array, and finds the gifts matching the criteria.

Uploaded by

ROHAN CHOPDE
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

Java Gift Price Comparison Program

This Java code defines a Gift class and methods to find the lowest priced gift by a given brand and the third highest priced gift. It takes gift details as input, stores them in an array, and finds the gifts matching the criteria.

Uploaded by

ROHAN CHOPDE
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import [Link].

Scanner;

import [Link];

public class Solution {

public static void main(String[] args) {

Scanner sc=new Scanner([Link]);

Gift[] gifts=new Gift[5];

for (int i = 0; i <5 ; i++) {

int a=[Link]();[Link]();

String b=[Link]();

int c=[Link]();[Link]();

String d=[Link]();

gifts[i]= new Gift(a,b,c,d);

String input=[Link]();

Gift ans1=getLowestPricedGiftByBrand(gifts,input);

if(ans1==null)

[Link]("No such gift found");

else {

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

Gift ans2= getThirdHighestPricedGift(gifts);


if(ans2==null)

[Link]("No such gift found");

else {

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

public static Gift getLowestPricedGiftByBrand(Gift[] gifts,String input)

int low=Integer.MAX_VALUE;

for (int i = 1; i <[Link] ; i++) {

if(gifts[i].getBrand().equalsIgnoreCase(input))

if(gifts[i].getPrice()<low)

low=gifts[i].getPrice();

}
for (int i = 0; i <[Link] ; i++) {

if(gifts[i].getPrice()==low)

return gifts[i];

return null;

public static Gift getThirdHighestPricedGift(Gift[] gifts)

int[] help=new int[0];

for (int i = 0; i <[Link] ; i++) {

if(gifts[i].getPrice()<1000 && gifts[i].getPrice()%2!=0 )

help=[Link](help,[Link]+1);

help[[Link]-1]=gifts[i].getPrice();

[Link](help);

if([Link]<=2)

return null;

int thp=help[[Link]-2];
for (int i = 0; i <[Link] ; i++) {

if(gifts[i].getPrice()==thp)

return gifts[i];

return null;

class Gift

private int giftId;

private String giftName;

private int price;

private String brand;

public Gift(int giftId, String giftName, int price, String brand) {

[Link] = giftId;

[Link] = giftName;

[Link] = price;

[Link] = brand;

public int getGiftId() {


return giftId;

public void setGiftId(int giftId) {

[Link] = giftId;

public String getGiftName() {

return giftName;

public void setGiftName(String giftName) {

[Link] = giftName;

public int getPrice() {

return price;

public void setPrice(int price) {

[Link] = price;

public String getBrand() {

return brand;

public void setBrand(String brand) {

[Link] = brand;

}
}

Common questions

Powered by AI

To handle a dynamic number of gifts, instead of a fixed-size array, use a dynamic data structure like `ArrayList<Gift>`. This allows adding elements without predefined limits. Modify any array-specific operations to incorporate list methods, such as using `add()` for insertion and employing lambda expressions or collections utility methods for filtering or sorting tasks. This approach enables scalability and adaptability to various input sizes, leveraging the collection's inherent capacity management and streamlining gift processing procedures .

The `Gift` class adheres well to the principles of encapsulation by keeping its fields private and providing public accessors and mutators. However, it could be improved in terms of modularity and single-responsibility principle by separating behavior from data. For example, any methods for manipulating gift collections (e.g., finding minimum or maximum prices) might be better suited in a different class to maintain `Gift` as a simple data model. As the `Gift` class focuses on encapsulating gift attributes, it aligns with core object-oriented principles but presents room for design enhancements regarding behavior segregation .

The `Solution` class does not explicitly apply any classical design patterns, but an opportunity for applying the Factory pattern could be present. Although object creation occurs directly within the main method, using a factory pattern for creating and initializing `Gift` objects could decrease coupling between the `Solution` class and `Gift` initialization details. In terms of the `Gift` class, no design patterns are visibly applied. For better object state management, the Builder pattern might be appropriate if the class becomes more complex or if init parameters increase. Currently, the lack of pattern usage might indicate simplicity but at the cost of flexibility and scalability .

The `Gift` class achieves encapsulation through the use of private fields (`giftId`, `giftName`, `price`, `brand`) and public getter and setter methods for these fields. This encapsulation allows the data within a `Gift` object to be accessed and modified only through these methods, providing control over how the data is manipulated and protecting it from unintended modifications directly from outside the class. This design promotes maintainability and robustness in code, as internal changes within the class do not affect external code directly relying on these public interfaces .

Code redundancy in methods such as `getLowestPricedGiftByBrand` and `getThirdHighestPricedGift` can be reduced by abstracting common functionality into helper methods. For instance, the code that filters and processes gift prices could be extracted into a method that accepts filtering criteria as parameters and returns an array of prices fitting that criteria. Furthermore, sorting and selecting operations on arrays could also be encapsulated within a generalized utility method, thereby reducing direct repetitions of logic and improving maintainability .

Enhancing the input handling process in `Solution` can involve implementing input validation to ensure that `Gift` attributes like `price` are integers within a reasonable range and strings aren't empty. Employing exception handling around input parsing can prevent the application from crashing due to malformed input. Furthermore, prompting users for confirmation or providing sample input formats improves UX and reduces errors. Integrating a loop for repeated input prompts on invalid entry can further build robustness into the user interaction process .

The implementation of the `getLowestPricedGiftByBrand` function contains a logical error where it does not correctly handle finding the lowest priced gift due to not updating the index during the final selection loop (the first loop index starts at 1 instead of 0). Consequently, errors can occur when there is a gift from the specified brand at position 0 in the array. Additionally, it fails to address potential cases where multiple gifts have the same minimum price; it always returns the one found first. These issues can lead to incorrect or unintended results being returned for gifts .

The `getLowestPricedGiftByBrand` function iterates over the list of `Gift` objects to find gifts that match the provided brand (ignoring case) and identifies the one with the lowest price. Initially, it sets a variable `low` to the maximum integer value. During iteration, if it finds a gift of the specified brand and its price is lower than `low`, it updates `low` with the gift's price. After the loop, it iterates again to find and return the full `Gift` object corresponding to this lowest price. If no gift is found for the brand, it returns null .

The `getThirdHighestPricedGift` function filters gifts by checking if their price is less than 1000 and if their price is an odd number. If a gift meets these criteria, its price is added to an array called `help`. After populating the array, the function sorts it and attempts to retrieve the third-highest price by selecting the second-to-last element of the sorted list, due to zero-based indexing. It returns the `Gift` object that matches this third-highest price. If there are fewer than three eligible prices, it returns null .

The robustness of the `getThirdHighestPricedGift` function could be improved by handling cases where there are fewer than three unique odd-priced gifts under 1000. This could involve adding condition checks after array creation to ensure the array has enough distinct elements before attempting to sort and retrieve prices. Implementing a set data structure instead of an array could help in automatically handling duplicates, thus simplifying the uniqueness management. Additionally, checking for arrays out of bounds or reliance solely on the sorted array's length without assuring distinct value count might lead to safer operations .

You might also like