2 Commits
Author SHA1 Message Date
Saba_frm c2bdebd5fa develop 2026-06-08 13:05:33 +03:30
Saba_frm 92adb3c784 develop 2026-06-08 12:59:57 +03:30
3 changed files with 133 additions and 80 deletions
+37 -15
View File
@@ -4,42 +4,64 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Scanner; import java.util.Scanner;
public class Main { public class Main
{
static ArrayList<Product> productCatalog = new ArrayList<>(); static ArrayList<Product> productCatalog = new ArrayList<>();
public static void loadProducts() throws IOException{
public static void loadProducts() throws IOException
{
InputStream input = Main.class InputStream input = Main.class
.getClassLoader() .getClassLoader()
.getResourceAsStream("products.csv"); .getResourceAsStream("products.csv");
if (input == null) {
if (input == null)
{
throw new IOException("products.csv not found"); throw new IOException("products.csv not found");
} }
Scanner scanner = new Scanner(input);
// TODO: try (Scanner scanner = new Scanner(input))
// - Read each line from products.csv {
// - For each line, parse productId, name, and price while (scanner.hasNextLine())
// - The format of the file is like this: {
// [productId],[name],[price] String line = scanner.nextLine();
// - Store Product objects in the productCatalog ArrayList
// NOTE if (line.trim().isEmpty()) continue;
// - The data in products.csv is guaranteed to be valid.
String[] parts = line.split(",");
if (parts.length >= 3)
{
int productId = Integer.parseInt(parts[0].trim());
String name = parts[1].trim();
double price = Double.parseDouble(parts[2].trim());
productCatalog.add(new Product(productId, name, price));
}
}
}
} }
public static void main(String[] args) public static void main(String[] args)
{ {
try { try
{
loadProducts(); loadProducts();
} catch (IOException e) { } catch (IOException e)
System.err.println("Error reading products"); {
System.err.println("Error reading products: " + e.getMessage());
System.out.println("Terminating the program..."); System.out.println("Terminating the program...");
return; return;
} }
System.out.println("=== Products loaded"); System.out.println("=== Products loaded");
ReportGenerator reportGenerator = new ReportGenerator("2025_order_details.csv", Collections.unmodifiableList(productCatalog)); ReportGenerator reportGenerator = new ReportGenerator("2025_order_details.csv", Collections.unmodifiableList(productCatalog));
reportGenerator.processFile(); reportGenerator.processFile();
System.out.println("=== Order file processed"); System.out.println("=== Order file processed");
reportGenerator.saveReport(); reportGenerator.saveReport();
System.out.println("=== Report saved as report.txt"); System.out.println("=== Report saved as report.txt");
} }
+11 -5
View File
@@ -1,23 +1,29 @@
public class Product { public class Product
{
private final int productID; private final int productID;
private final String productName; private final String productName;
private final double price; private final double price;
public Product(int productID, String productName, double price) { public Product(int productID, String productName, double price)
{
this.productID = productID; this.productID = productID;
this.productName = productName; this.productName = productName;
this.price = price; this.price = price;
} }
public int getProductID() { public int getProductID()
{
return productID; return productID;
} }
public String getProductName() { public String getProductName()
{
return productName; return productName;
} }
public double getPrice() { public double getPrice()
{
return price; return price;
} }
} }
+84 -59
View File
@@ -1,6 +1,12 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List; import java.util.List;
public class ReportGenerator { public class ReportGenerator
{
private final String ordersFilePath; private final String ordersFilePath;
private final List<Product> productList; private final List<Product> productList;
@@ -10,74 +16,93 @@ public class ReportGenerator {
private double totalDiscountValue; private double totalDiscountValue;
private int totalInvalidLines; private int totalInvalidLines;
public ReportGenerator(String ordersFilePath, List<Product> productList) { public ReportGenerator(String ordersFilePath, List<Product> productList)
{
this.ordersFilePath = ordersFilePath; this.ordersFilePath = ordersFilePath;
this.productList = productList; this.productList = productList;
} }
public void processFile() public void processFile()
{ {
// TODO: try (BufferedReader reader = new BufferedReader(new FileReader(ordersFilePath)))
// 1. Open the order details CSV file {
// 2. Read the file line by line
// 3. Split each line using comma delimiter String line;
// (each line is guaranteed to contain exactly two commas)
// 4. Each line contains exactly 3 values in the format: while ((line = reader.readLine()) != null)
// [productId],[quantity],[discountPercent] {
// 5. Attempt to convert values: try
// - productId -> int {
// - quantity -> int String[] parts = line.split(",");
// - discountPercent -> int
// NOTE: int productId = Integer.parseInt(parts[0].trim());
// - quantity and discountPercent may contain invalid characters int quantity = Integer.parseInt(parts[1].trim());
// (e.g., letters instead of numbers). int discountPercent = Integer.parseInt(parts[2].trim());
// - If parsing any value fails (NumberFormatException),
// the entire line must be considered invalid. if (productId <= 0 || quantity <= 0 || discountPercent < 0 || discountPercent > 99)
// - Use try-catch blocks and exception handling to safely {
// handle parsing and validation errors without stopping totalInvalidLines++;
// the processing of the remaining lines. continue;
// 6. Validate parsed values: }
// - productId must be greater than 0
// - quantity must be greater than 0 Product product = findProductById(productId);
// - discountPercent must be between 0 and 99 inclusive
// 7. Look for a Product in productList that matches productId if (product == null)
// 8. If no Product with that ID exists in the catalog, {
// the entire line is considered invalid totalInvalidLines++;
// 9. If all values are valid and the product exists, calculate: continue;
// subtotal = quantity * product price }
// discountValue = subtotal * discountPercent / 100
// finalCost = subtotal - discountValue double subtotal = quantity * product.getPrice();
// 10. Update report totals: double discountValue = subtotal * discountPercent / 100.0;
// - totalQuantity += quantity double finalCost = subtotal - discountValue;
// - totalFinalCost += finalCost
// - totalDiscountValue += discountValue totalQuantity += quantity;
// 11. If any parsing error, validation failure, or missing product occurs: totalDiscountValue += discountValue;
// - increment totalInvalidLines totalFinalCost += finalCost;
// - skip the line and continue processing the next line
// 12. Close all file resources } catch (NumberFormatException | ArrayIndexOutOfBoundsException e)
{
totalInvalidLines++;
}
}
} catch (IOException e)
{
System.out.println("Error reading file: " + e.getMessage());
}
} }
private Product findProductById(int productId)
{
for (Product product : productList)
{
if (product.getProductID() == productId)
{
return product;
}
}
return null;
}
public void saveReport() public void saveReport()
{ {
// TODO: try (PrintWriter writer = new PrintWriter(new FileWriter("report.txt")))
// 1. Build a formatted report string {
// 2. Include:
// - total quantity
// - total final cost
// - total discount value
// - total invalid lines
// 3. Create/open output report file (name it report.txt)
// 4. Write report string into file
// 5. Handle file writing exceptions
// 6. Close writer resources
/* Example Structure writer.println("========= SALES REPORT =========");
========= SALES REPORT ========= writer.println("Total Quantity Sold: " + totalQuantity);
Total Quantity Sold: 42 writer.printf("Total Final Cost: $%.2f%n", totalFinalCost);
Total Final Cost: $1520.75 writer.printf("Total Discount Value: $%.2f%n", totalDiscountValue);
Total Discount Value: $230.50 writer.println("Invalid Rows: " + totalInvalidLines);
Invalid Rows: 3 writer.println("================================");
================================
*/ } catch (IOException e)
{
System.out.println("Error writing report: " + e.getMessage());
}
} }
} }