implement saveReport method

This commit is contained in:
2026-05-16 18:17:22 +03:30
parent 64bfeb594d
commit eba86e7ca5
2 changed files with 24 additions and 27 deletions
+1
View File
@@ -15,6 +15,7 @@ public class Main {
}
Scanner scanner = new Scanner(input);
//reading file line by line and then parsing their values
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] cells = line.split(",");
+23 -27
View File
@@ -1,4 +1,5 @@
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
@@ -35,29 +36,29 @@ public class ReportGenerator {
int quantity = Integer.parseInt(fields[1]);
int discountPercent = Integer.parseInt(fields[2]);
// check if any field has wrong amounts
if ((discountPercent < 0 || discountPercent > 100) || (quantity <= 0) || (!productList.contains(productID)))
if ((discountPercent < 0 || discountPercent > 99) || (quantity <= 0) ||
(productList.stream().noneMatch(product -> product.getProductID() == productID)))
{ throw new IllegalArgumentException(); }
double subtotal = quantity * discountPercent / 100;
Product p = productList.stream().filter(product -> product.getProductID() == productID).findFirst().get();
double subtotal = quantity * p.getPrice();
double discountValue = subtotal * discountPercent / 100;
double finalCost = subtotal + discountValue;
double finalCost = subtotal - discountValue;
//updating report attributes
totalQuantity += quantity;
totalFinalCost += finalCost;
totalDiscountValue += discountValue;
}
catch (Exception e) {
catch (IllegalArgumentException e) {
totalInvalidLines++;
System.out.println("Inavalid line: " + lineNumber);
continue;
}
finally {
input.close();
}
}
input.close();
}
catch (IOException e) {
System.out.println("Orders file not found");
}
@@ -66,26 +67,21 @@ public class ReportGenerator {
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
================================
*/
String report = "========= SALES REPORT =========\n" +
"Total Quantity Sold: " + totalQuantity + "\n" +
"Total Final Cost: " + totalFinalCost + "\n" +
"Total Discount Value: " + totalDiscountValue + "\n" +
"Total Invalid Rows: " + totalInvalidLines + "\n" +
"=======================================";
try {
PrintWriter output = new PrintWriter("report.txt");
output.println(report);
output.close();
}
catch (FileNotFoundException e) {
System.out.println("Error writing report file!");
}
}
}