Let us create this program using hashMap. A list of products with its prices are added to the hashMap.
Steps:
- · Import the built-in packages java.util.HashMap,java.util.Map.
- · A public class is developed with main() function.
- · Constructor: initializes the object.
- · addItems() : it inserts the product and price.
- · getPrice() : This function gets the price for the product.
- · updatePrice(): it updates the price.
- · printPrice() : This function prints the product and price.
Program:
// import the built-in packages
import java.util.HashMap;
import java.util.Map;
//Create a public class
public class ProductPricesPrint {
private
Map<String, Double> prices;
//constructor of the class to initialise the object.
public
ProductPricesPrint() {
prices = new
HashMap<>();
}
//Member function addItem()
public void
addItem(String Product, double price) {
prices.put(Product, price);
}
//Member function getPrice()
public Double
getPrice(String Product) {
return
prices.get(Product);
}
//updatePrice() function to update the value.
public void
updatePrice(String Product, double newPrice) {
if
(prices.containsKey(Product)) {
prices.put(Product, newPrice);
}
}
//To print the product list
public void
printPrice(String Product) {
Double price =
prices.get(Product);
if (price !=
null) {
System.out.println("The price of " + Product + " is:
" + price);
} else {
System.out.println(Product + " is not available.");
}
}
//Main() function definition
public static void
main(String[] args) {
ProductPricesPrint productPricesPrint = new ProductPricesPrint();
productPricesPrint.addItem("Cricket bat", 1500);
productPricesPrint.addItem("Cricket ball",200);
productPricesPrint.addItem("Hockey Bat",1000);
productPricesPrint.addItem("Hockey Ball",240);
productPricesPrint.addItem("FootBall",500);
productPricesPrint.addItem("BasketBall",450);
productPricesPrint.printPrice("BasketBall");
productPricesPrint.printPrice("carrom");
}
}
Output:
C:\raji\blog>javac ProductPricesPrint.java
C:\raji\blog>java ProductPricesPrint.java
The price of BasketBall is: 450.0
carrom is not available.
This is the way of checking a product list is available in
the list or not. Keep coding!!!