Exceptions and Files

This commit is contained in:
2026-05-22 12:39:26 +03:30
parent 8e6d1d1760
commit 7367de1e6a
2 changed files with 99 additions and 84 deletions
+32 -16
View File
@@ -4,42 +4,58 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public class Main
{
static ArrayList<Product> productCatalog = new ArrayList<>();
public static void loadProducts() throws IOException{
public static void loadProducts() throws IOException
{
InputStream input = Main.class
.getClassLoader()
.getResourceAsStream("products.csv");
if (input == null) {
if (input == null)
{
throw new IOException("products.csv not found");
}
Scanner scanner = new Scanner(input);
// TODO:
// - Read each line from products.csv
// - For each line, parse productId, name, and price
// - The format of the file is like this:
// [productId],[name],[price]
// - Store Product objects in the productCatalog ArrayList
try (Scanner scanner = new Scanner(input))
{
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
if (line.isBlank()) continue;
// NOTE
// - The data in products.csv is guaranteed to be valid.
String[] parts = line.split(",");
int id = Integer.parseInt(parts[0].trim());
String name = parts[1].trim();
double price = Double.parseDouble(parts[2].trim());
productCatalog.add(new Product(id, name, price));
}
}
}
public static void main(String[] args)
{
try {
loadProducts();
} catch (IOException e) {
try
{loadProducts();}
catch (IOException e)
{
System.err.println("Error reading products");
System.out.println("Terminating the program...");
return;
}
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();
System.out.println("=== Order file processed");
reportGenerator.saveReport();
System.out.println("=== Report saved as report.txt");
}
+66 -67
View File
@@ -1,83 +1,82 @@
import java.util.List;
public class ReportGenerator {
import java.io.*;
import java.util.*;
public class ReportGenerator
{
private final String ordersFilePath;
private final List<Product> productList;
private double totalFinalCost = 0.0;
private int totalQuantity = 0;
private double totalDiscountValue = 0.0;
private int totalInvalidLines = 0;
private double totalFinalCost;
private int totalQuantity;
private double totalDiscountValue;
private int totalInvalidLines;
public ReportGenerator(String ordersFilePath, List<Product> productList) {
public ReportGenerator(String ordersFilePath, List<Product> productList)
{
this.ordersFilePath = ordersFilePath;
this.productList = productList;
}
public void processFile()
{
// TODO:
// 1. Open the order details CSV file
// 2. Read the file line by line
// 3. Split each line using comma delimiter
// (each line is guaranteed to contain exactly two commas)
// 4. Each line contains exactly 3 values in the format:
// [productId],[quantity],[discountPercent]
// 5. Attempt to convert values:
// - productId -> int
// - quantity -> int
// - discountPercent -> int
// NOTE:
// - quantity and discountPercent may contain invalid characters
// (e.g., letters instead of numbers).
// - If parsing any value fails (NumberFormatException),
// the entire line must be considered invalid.
// - Use try-catch blocks and exception handling to safely
// handle parsing and validation errors without stopping
// the processing of the remaining lines.
// 6. Validate parsed values:
// - productId must be greater than 0
// - quantity must be greater than 0
// - discountPercent must be between 0 and 99 inclusive
// 7. Look for a Product in productList that matches productId
// 8. If no Product with that ID exists in the catalog,
// the entire line is considered invalid
// 9. If all values are valid and the product exists, calculate:
// subtotal = quantity * product price
// discountValue = subtotal * discountPercent / 100
// finalCost = subtotal - discountValue
// 10. Update report totals:
// - totalQuantity += quantity
// - totalFinalCost += finalCost
// - totalDiscountValue += discountValue
// 11. If any parsing error, validation failure, or missing product occurs:
// - increment totalInvalidLines
// - skip the line and continue processing the next line
// 12. Close all file resources
Map<Integer, Product> productMap = new HashMap<>();
for (Product p : productList)
{
productMap.put(p.getProductID(), p);
}
try (BufferedReader reader = new BufferedReader(new FileReader(ordersFilePath)))
{
String line;
while ((line = reader.readLine()) != null)
{
try
{
String[] parts = line.split(",");
if (parts.length != 3) throw new Exception("Invalid format");
int productId = Integer.parseInt(parts[0].trim());
int quantity = Integer.parseInt(parts[1].trim());
int discountPercent = Integer.parseInt(parts[2].trim());
Product product = productMap.get(productId);
if (productId <= 0 || quantity <= 0 || discountPercent < 0 || discountPercent > 99 || product == null)
{
throw new Exception("Validation failed");
}
double subtotal = quantity * product.getPrice();
double discountVal = subtotal * discountPercent / 100.0;
double finalCost = subtotal - discountVal;
totalQuantity += quantity;
totalFinalCost += finalCost;
totalDiscountValue += discountVal;
}
catch (Exception e) {totalInvalidLines++;}
}
}
catch (IOException e)
{
System.err.println("Error reading file: " + e.getMessage());
}
}
public void saveReport()
{
// TODO:
// 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
========= SALES REPORT =========
Total Quantity Sold: 42
Total Final Cost: $1520.75
Total Discount Value: $230.50
Invalid Rows: 3
================================
*/
try (PrintWriter writer = new PrintWriter(new FileWriter("report.txt")))
{
writer.println("========= SALES REPORT =========");
writer.println("Total Quantity Sold: " + totalQuantity);
writer.printf("Total Final Cost: $%.2f%n", totalFinalCost);
writer.printf("Total Discount Value: $%.2f%n", totalDiscountValue);
writer.println("Invalid Rows: " + totalInvalidLines);
writer.println("================================");
}
catch (IOException e)
{
System.err.println("Error writing report: " + e.getMessage());
}
}
}