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

104 lines
3.5 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 InvalidLines;
public ReportGenerator(String ordersFilePath, List<Product> productList) {
this.ordersFilePath = ordersFilePath;
this.productList = productList;
}
public void processFile()
{
//opening and doing the math
try {
File source = new File(ordersFilePath);
Scanner scanner = new Scanner(source);
//
while (scanner.hasNextLine()) {
int productId;
int count;
int discountPercentage;
String line = scanner.nextLine();
String[] parts = line.split(",");
try {
productId = Integer.parseInt(parts[0].trim());
if (productId < 1 || productId > productList.size()) {
InvalidLines++;
continue;
}
} catch (NumberFormatException e) {
InvalidLines++;
continue;
}
try {
count = Integer.parseInt(parts[1].trim());
if(count < 1) {
InvalidLines++;
continue;
}
} catch (NumberFormatException e) {
InvalidLines++;
continue;
}
try {
discountPercentage = Integer.parseInt(parts[2].trim());
if (discountPercentage < 0 || discountPercentage > 99) {
InvalidLines++;
continue;
}
} catch (NumberFormatException e) {
InvalidLines++;
continue;
}
//computing the results
double cost = count * productList.get(productId - 1).getPrice();
double discount = count * productList.get(productId - 1).getPrice() * discountPercentage / 100;
totalFinalCost += cost - discount;
totalDiscountValue += discount;
totalQuantity += count;
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void saveReport()
{
String report =
"===== SALES REPORT =====\n" +
"Total Quantity: " + totalQuantity + "\n" +
"Total Final Cost: $" + String.format("%.2f", totalFinalCost) + "\n" +
"Total Discount: $" + String.format("%.2f", totalDiscountValue) + "\n" +
"Invalid Lines: " + InvalidLines + "\n" +
"=========================\n";
try
{
FileWriter fileWriter = new FileWriter("output.txt");
fileWriter.write(report);
fileWriter.close();
}
catch (IOException e)
{
System.out.println("Error in outputting report: " + e.getMessage());
}
}
}