Files
HW-06-exceptions-and-file-h…/src/main/java/ReportGenerator.java
T

104 lines
3.2 KiB
Java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
public class ReportGenerator {
private final String ordersFilePath;
private final List<Product> productList;
private double totalFinalCost;
private int totalQuantity;
private double totalDiscountValue;
private int totalInvalidLines;
public ReportGenerator(String ordersFilePath, List<Product> productList) {
this.ordersFilePath = ordersFilePath;
this.productList = productList;
}
public void processFile()
{
File file = new File(ordersFilePath);
if(!file.exists())
{
System.err.println("File is not found!");
return;
}
try(Scanner scanner = new Scanner(file))
{
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
if(line.isBlank()) continue;
try
{
String[] parts = line.split(",");
int productId = Integer.parseInt(parts[0].trim());
int quantity = Integer.parseInt(parts[1].trim());
int discountPercent = Integer.parseInt(parts[2].trim());
if( quantity<=0 || discountPercent < 0 || discountPercent >99)
{
throw new Exception("invalid value!");
}
Product product = null;
for (Product p : productList)
{
if(p.getProductID() == productId)
{
product = p;
break;
}
}
if(product == null)
{
throw new Exception("Product not found");
}
double subtotal = quantity * product.getPrice();
double discountValue = subtotal * discountPercent / 100;
double finalCost = subtotal - discountValue;
totalQuantity += quantity;
totalFinalCost += finalCost;
totalDiscountValue += discountValue;
}
catch (Exception e)
{
totalInvalidLines++;
}
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
public void saveReport() throws IOException {
String report = "========= SALES REPORT =========\n" +
"Total Quantity: " + totalQuantity + "\n" +
"Total Final Cost: " + totalFinalCost + "\n" +
"Total Discount Value: " + totalDiscountValue + "\n" +
"Invalid Lines: " + totalInvalidLines + "\n" +
"================================";
try
{
FileWriter writer = new FileWriter("report.txt");
writer.write(report);
writer.close();
}
catch (IOException e)
{
System.err.println("ERROR!");
}
}
}