Merge PR 'Complete Home Work 6 and file handling tasks' (#1) from develop into main

Full Mark
This commit was merged in pull request #1.
This commit is contained in:
2026-07-10 19:32:50 +00:00
2 changed files with 73 additions and 66 deletions
+9 -9
View File
@@ -15,15 +15,15 @@ public class Main {
} }
Scanner scanner = new Scanner(input); Scanner scanner = new Scanner(input);
// TODO: while (scanner.hasNextLine()) {
// - Read each line from products.csv String line = scanner.nextLine();
// - For each line, parse productId, name, and price String[] parts = line.split(",");
// - The format of the file is like this: int productId = Integer.parseInt(parts[0]);
// [productId],[name],[price] String name = parts[1];
// - Store Product objects in the productCatalog ArrayList double price = Double.parseDouble(parts[2]);
productCatalog.add(new Product(productId, name, price));
// NOTE }
// - The data in products.csv is guaranteed to be valid. scanner.close();
} }
public static void main(String[] args) public static void main(String[] args)
+64 -57
View File
@@ -1,3 +1,8 @@
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 {
@@ -17,67 +22,69 @@ public class ReportGenerator {
public void processFile() public void processFile()
{ {
// TODO: try {
// 1. Open the order details CSV file BufferedReader reader = new BufferedReader(new FileReader(ordersFilePath));
// 2. Read the file line by line String line;
// 3. Split each line using comma delimiter
// (each line is guaranteed to contain exactly two commas) while ((line = reader.readLine()) != null) {
// 4. Each line contains exactly 3 values in the format: try {
// [productId],[quantity],[discountPercent] String[] parts = line.split(",");
// 5. Attempt to convert values: int productId = Integer.parseInt(parts[0]);
// - productId -> int int quantity = Integer.parseInt(parts[1]);
// - quantity -> int int discountPercent = Integer.parseInt(parts[2]);
// - discountPercent -> int
// NOTE: if (quantity <= 0 || discountPercent < 0 || discountPercent > 99) {
// - quantity and discountPercent may contain invalid characters totalInvalidLines++;
// (e.g., letters instead of numbers). continue;
// - If parsing any value fails (NumberFormatException), }
// the entire line must be considered invalid.
// - Use try-catch blocks and exception handling to safely Product foundProduct = null;
// handle parsing and validation errors without stopping for (Product p : productList) {
// the processing of the remaining lines. if (p.getProductID() == productId) {
// 6. Validate parsed values: foundProduct = p;
// - productId must be greater than 0 break;
// - 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, if (foundProduct == null) {
// 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 * foundProduct.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: totalFinalCost += finalCost;
// - increment totalInvalidLines totalDiscountValue += discountValue;
// - skip the line and continue processing the next line
// 12. Close all file resources } catch (NumberFormatException e) {
totalInvalidLines++;
}
}
reader.close();
} catch (IOException e) {
System.err.println("Error reading order file: " + e.getMessage());
}
} }
public void saveReport() public void saveReport()
{ {
// TODO: try {
// 1. Build a formatted report string PrintWriter writer = new PrintWriter(new FileWriter("report.txt"));
// 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("================================");
================================
*/ writer.close();
} catch (IOException e) {
System.err.println("Error writing report: " + e.getMessage());
}
} }
} }