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
+33 -17
View File
@@ -4,43 +4,59 @@ 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 if (line.isBlank()) continue;
// NOTE String[] parts = line.split(",");
// - The data in products.csv is guaranteed to be valid.
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) 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");
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");
} }
} }
+66 -67
View File
@@ -1,83 +1,82 @@
import java.util.List; import java.io.*;
import java.util.*;
public class ReportGenerator {
public class ReportGenerator
{
private final String ordersFilePath; private final String ordersFilePath;
private final List<Product> productList; 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; public ReportGenerator(String ordersFilePath, List<Product> productList)
private int totalQuantity; {
private double totalDiscountValue;
private int totalInvalidLines;
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: Map<Integer, Product> productMap = new HashMap<>();
// 1. Open the order details CSV file for (Product p : productList)
// 2. Read the file line by line {
// 3. Split each line using comma delimiter productMap.put(p.getProductID(), p);
// (each line is guaranteed to contain exactly two commas) }
// 4. Each line contains exactly 3 values in the format:
// [productId],[quantity],[discountPercent] try (BufferedReader reader = new BufferedReader(new FileReader(ordersFilePath)))
// 5. Attempt to convert values: {
// - productId -> int String line;
// - quantity -> int while ((line = reader.readLine()) != null)
// - discountPercent -> int {
// NOTE: try
// - quantity and discountPercent may contain invalid characters {
// (e.g., letters instead of numbers). String[] parts = line.split(",");
// - If parsing any value fails (NumberFormatException), if (parts.length != 3) throw new Exception("Invalid format");
// the entire line must be considered invalid.
// - Use try-catch blocks and exception handling to safely int productId = Integer.parseInt(parts[0].trim());
// handle parsing and validation errors without stopping int quantity = Integer.parseInt(parts[1].trim());
// the processing of the remaining lines. int discountPercent = Integer.parseInt(parts[2].trim());
// 6. Validate parsed values:
// - productId must be greater than 0 Product product = productMap.get(productId);
// - quantity must be greater than 0
// - discountPercent must be between 0 and 99 inclusive if (productId <= 0 || quantity <= 0 || discountPercent < 0 || discountPercent > 99 || product == null)
// 7. Look for a Product in productList that matches productId {
// 8. If no Product with that ID exists in the catalog, throw new Exception("Validation failed");
// the entire line is considered invalid }
// 9. If all values are valid and the product exists, calculate:
// subtotal = quantity * product price double subtotal = quantity * product.getPrice();
// discountValue = subtotal * discountPercent / 100 double discountVal = subtotal * discountPercent / 100.0;
// finalCost = subtotal - discountValue double finalCost = subtotal - discountVal;
// 10. Update report totals:
// - totalQuantity += quantity totalQuantity += quantity;
// - totalFinalCost += finalCost totalFinalCost += finalCost;
// - totalDiscountValue += discountValue totalDiscountValue += discountVal;
// 11. If any parsing error, validation failure, or missing product occurs:
// - increment totalInvalidLines }
// - skip the line and continue processing the next line catch (Exception e) {totalInvalidLines++;}
// 12. Close all file resources }
}
catch (IOException e)
{
System.err.println("Error reading file: " + e.getMessage());
}
} }
public void saveReport() public void saveReport()
{ {
// TODO: try (PrintWriter writer = new PrintWriter(new FileWriter("report.txt")))
// 1. Build a formatted report string {
// 2. Include: writer.println("========= SALES REPORT =========");
// - total quantity writer.println("Total Quantity Sold: " + totalQuantity);
// - total final cost writer.printf("Total Final Cost: $%.2f%n", totalFinalCost);
// - total discount value writer.printf("Total Discount Value: $%.2f%n", totalDiscountValue);
// - total invalid lines writer.println("Invalid Rows: " + totalInvalidLines);
// 3. Create/open output report file (name it report.txt) writer.println("================================");
// 4. Write report string into file }
// 5. Handle file writing exceptions catch (IOException e)
// 6. Close writer resources {
System.err.println("Error writing report: " + e.getMessage());
/* Example Structure }
========= SALES REPORT =========
Total Quantity Sold: 42
Total Final Cost: $1520.75
Total Discount Value: $230.50
Invalid Rows: 3
================================
*/
} }
} }