QUESTION 2:
Process Product Data from a CSV File
Problem Statement:
Write a Java program to perform the following tasks:
1.Create a price tracker for an e-commerce platform where:
Each product has a product ID, name, and price.
The platform allows updating the price of a product frequently.
Tasks:
Use a suitable collection to:
Add new products.
Update the price of an existing product.
Retrieve the price of a product by its ID.
Display the product details sorted by their prices.
Challenge:
What if multiple products have the same price? How would you sort them?
Read Product Data:
Read product data from a CSV file named products.csv.
Each line in the file represents a product and contains the following details:
Product Number: An integer representing the unique ID of the product.
Product Name: A string representing the name of the product.
Price: A double representing the price of the product.
Example format of the CSV file:
101,Smartphone,12000.50
102,Laptop,45000.00
103,Tablet,8000.75
104,Smartwatch,3500.00
105,Headphones,2500.00
Store Product Data in a List:
Read the product data from the file and store it in a list of Product objects.
Create a Product class with the following attributes:
productNumber (int)
productName (String)
price (double)
Sort the Products:
Sort the list of products in two ways using comparators:
By product number (in ascending order).
By price (in ascending order).
Display the sorted lists.
Filter Products:
Filter products from the list where the price is greater than 5000.
Insert into Database:
Insert the filtered products into a database table named Products with the
following structure:
CREATE TABLE Products (
ProductNumber INT PRIMARY KEY,
ProductName VARCHAR(100),
Price DOUBLE
);
Use JDBC to connect to the database and perform the insertion.
Print a message for each product inserted into the database.
Ensure the program handles exceptions and logs errors for any issues encountered
(e.g., file reading errors, database errors)
===================================================================================
=========================================
PROGRAM :
================
import java.io.*;
import java.sql.*;
import java.util.*;
class Product {
private int productNumber;
private String productName;
private double price;
public Product(int productNumber, String productName, double price) {
this.productNumber = productNumber;
this.productName = productName;
this.price = price;
}
public int getProductNumber() {
return productNumber;
}
public String getProductName() {
return productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product Number: " + productNumber + ", Product Name: " +
productName + ", Price: " + price;
}
}
public class PriceTrackerApp {
private static List<Product> productList = new ArrayList<>();
public static void main(String[] args) {
try {
// Step 1: Read data from CSV file
readProductsFromCSV("products.csv");
// Step 2: Display products sorted by product number
System.out.println("Products sorted by Product Number:");
productList.sort(Comparator.comparingInt(Product::getProductNumber));
productList.forEach(System.out::println);
// Step 3: Display products sorted by price (and by product number in
case of a tie)
System.out.println("\nProducts sorted by Price:");
productList.sort(Comparator.comparingDouble(Product::getPrice)
.thenComparing(Product::getProductNumber));
productList.forEach(System.out::println);
// Step 4: Insert all products into a database table
insertProductsIntoDatabase();
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
private static void readProductsFromCSV(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
String[] data = line.split(",");
int productNumber = Integer.parseInt(data[0].trim());
String productName = data[1].trim();
double price = Double.parseDouble(data[2].trim());
Product product = new Product(productNumber, productName, price);
productList.add(product);
}
reader.close();
}
private static void insertProductsIntoDatabase() {
String url = "jdbc:mysql://localhost:3306/ecommerce";
String user = "root";
String password = "password";
String createTableSQL = "CREATE TABLE IF NOT EXISTS Products (" +
"ProductNumber INT PRIMARY KEY, " +
"ProductName VARCHAR(100), " +
"Price DOUBLE)";
String insertSQL = "INSERT INTO Products (ProductNumber, ProductName,
Price) VALUES (?, ?, ?)";
try (Connection connection = DriverManager.getConnection(url, user,
password);
Statement statement = connection.createStatement();
PreparedStatement preparedStatement =
connection.prepareStatement(insertSQL)) {
// Create the table if it doesn't exist
statement.execute(createTableSQL);
// Insert products into the database
for (Product product : productList) {
preparedStatement.setInt(1, product.getProductNumber());
preparedStatement.setString(2, product.getProductName());
preparedStatement.setDouble(3, product.getPrice());
preparedStatement.executeUpdate();
System.out.println("Inserted: " + product);
}
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
INPUT:
101,Smartphone,12000.50
102,Laptop,45000.00
103,Tablet,8000.75
104,Smartwatch,3500.00
105,Headphones,2500.00
OUTPUT:
Products sorted by Product Number:
Product Number: 101, Product Name: Smartphone, Price: 12000.5
Product Number: 102, Product Name: Laptop, Price: 45000.0
Product Number: 103, Product Name: Tablet, Price: 8000.75
Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Product Number: 105, Product Name: Headphones, Price: 2500.0
Products sorted by Price:
Product Number: 105, Product Name: Headphones, Price: 2500.0
Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Product Number: 103, Product Name: Tablet, Price: 8000.75
Product Number: 101, Product Name: Smartphone, Price: 12000.5
Product Number: 102, Product Name: Laptop, Price: 45000.0
Inserted: Product Number: 101, Product Name: Smartphone, Price: 12000.5
Inserted: Product Number: 102, Product Name: Laptop, Price: 45000.0
Inserted: Product Number: 103, Product Name: Tablet, Price: 8000.75
Inserted: Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Inserted: Product Number: 105, Product Name: Headphones, Price: 2500.0
==================================================
Test Case 1: Read Products from CSV File
Input
CSV File: products.csv
101,Smartphone,12000.50
102,Laptop,45000.00
103,Tablet,8000.75
104,Smartwatch,3500.00
105,Headphones,2500.00
Expected Output:
Products read from CSV:
Product Number: 101, Product Name: Smartphone, Price: 12000.5
Product Number: 102, Product Name: Laptop, Price: 45000.0
Product Number: 103, Product Name: Tablet, Price: 8000.75
Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Product Number: 105, Product Name: Headphones, Price: 2500.0
=============================================================
Test Case 2: Sort Products by Product Number
Input
CSV File: products.csv
101,Smartphone,12000.50
102,Laptop,45000.00
103,Tablet,8000.75
104,Smartwatch,3500.00
105,Headphones,2500.00
Expected Output
Products sorted by Product Number:
Product Number: 101, Product Name: Smartphone, Price: 12000.5
Product Number: 102, Product Name: Laptop, Price: 45000.0
Product Number: 103, Product Name: Tablet, Price: 8000.75
Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Product Number: 105, Product Name: Headphones, Price: 2500.0
====================================================================
Test Case 3: Sort Products by Price
Input
CSV File: products.csv
101,Smartphone,12000.50
102,Laptop,45000.00
103,Tablet,8000.75
104,Smartwatch,3500.00
105,Headphones,2500.00
Expected Output
Products sorted by Price:
Product Number: 105, Product Name: Headphones, Price: 2500.0
Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Product Number: 103, Product Name: Tablet, Price: 8000.75
Product Number: 101, Product Name: Smartphone, Price: 12000.5
Product Number: 102, Product Name: Laptop, Price: 45000.0
=================================================================
Test Case 4: Add a New Product
Input
CSV File: products.csv
Add Product:
Product ID: 106
Product Name: Keyboard
Price: 2000.00
Expected Output
Adding a new product:
Added: Product Number: 106, Product Name: Keyboard, Price: 2000.0
Products sorted by Price after adding:
Product Number: 106, Product Name: Keyboard, Price: 2000.0
Product Number: 105, Product Name: Headphones, Price: 2500.0
Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Product Number: 103, Product Name: Tablet, Price: 8000.75
Product Number: 101, Product Name: Smartphone, Price: 12000.5
Product Number: 102, Product Name: Laptop, Price: 45000.0
==============================================================
Test Case 5: Update the Price of an Existing Product
Input
CSV File: products.csv
Update Product:
Product ID: 103
New Price: 9000.75
Expected Output
Updating the price of an existing product:
Updated Price: Product Number: 103, Product Name: Tablet, Price: 9000.75
Products sorted by Price after updating:
Product Number: 105, Product Name: Headphones, Price: 2500.0
Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Product Number: 103, Product Name: Tablet, Price: 9000.75
Product Number: 101, Product Name: Smartphone, Price: 12000.5
Product Number: 102, Product Name: Laptop, Price: 45000.0
==========================================
Test Case 6: Insert Products into Database
Input
CSV File: products.csv
Database Action: Insert all products into the database table.
Expected Output
Products inserted into the database:
Inserted: Product Number: 101, Product Name: Smartphone, Price: 12000.5
Inserted: Product Number: 102, Product Name: Laptop, Price: 45000.0
Inserted: Product Number: 103, Product Name: Tablet, Price: 8000.75
Inserted: Product Number: 104, Product Name: Smartwatch, Price: 3500.0
Inserted: Product Number: 105, Product Name: Headphones, Price: 2500.0