complete homework 6 exceptions and file handling logic #7
+26
-11
@@ -6,7 +6,8 @@ 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");
|
||||||
@@ -15,19 +16,33 @@ public class Main {
|
|||||||
}
|
}
|
||||||
Scanner scanner = new Scanner(input);
|
Scanner scanner = new Scanner(input);
|
||||||
|
|
||||||
// TODO:
|
// خواندن خط به خط فایل محصولات تا زمانی که خط بعدی وجود دارد
|
||||||
// - Read each line from products.csv
|
while (scanner.hasNextLine()) {
|
||||||
// - For each line, parse productId, name, and price
|
String line = scanner.nextLine();
|
||||||
// - The format of the file is like this:
|
|
||||||
// [productId],[name],[price]
|
|
||||||
// - Store Product objects in the productCatalog ArrayList
|
|
||||||
|
|
||||||
// NOTE
|
// اگر خط خالی بود برو سراغ خط بعدی که برنامه ارور ندهد
|
||||||
// - The data in products.csv is guaranteed to be valid.
|
if (line.trim().isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// جدا کردن اطلاعات هر خط بر اساس ویرگول
|
||||||
|
String[] tokens = line.split(",");
|
||||||
|
|
||||||
|
// تبدیل رشتهها به فرمت عددی مناسب (طبق داک پروژه دادههای این فایل همیشه معتبرند)
|
||||||
|
int id = Integer.parseInt(tokens[0].trim());
|
||||||
|
String name = tokens[1].trim();
|
||||||
|
double price = Double.parseDouble(tokens[2].trim());
|
||||||
|
|
||||||
|
// ساختن شیء محصول جدید و اضافه کردن آن به لیست کاتالوگ
|
||||||
|
Product currentProduct = new Product(id, name, price);
|
||||||
|
productCatalog.add(currentProduct);
|
||||||
|
}
|
||||||
|
|
||||||
|
// بستن اسکنر برای آزاد شدن فایل
|
||||||
|
scanner.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args)
|
public static void main(String[] args) {
|
||||||
{
|
|
||||||
try {
|
try {
|
||||||
loadProducts();
|
loadProducts();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
|
import java.io.FileWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.PrintWriter;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
public class ReportGenerator {
|
public class ReportGenerator {
|
||||||
|
|
||||||
@@ -15,69 +20,93 @@ public class ReportGenerator {
|
|||||||
this.productList = productList;
|
this.productList = productList;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void processFile()
|
public void processFile() {
|
||||||
{
|
InputStream input = getClass().getClassLoader().getResourceAsStream(ordersFilePath);
|
||||||
// TODO:
|
if (input == null) {
|
||||||
// 1. Open the order details CSV file
|
System.err.println("Orders file not found: " + ordersFilePath);
|
||||||
// 2. Read the file line by line
|
return;
|
||||||
// 3. Split each line using comma delimiter
|
}
|
||||||
// (each line is guaranteed to contain exactly two commas)
|
|
||||||
// 4. Each line contains exactly 3 values in the format:
|
Scanner scanner = new Scanner(input);
|
||||||
// [productId],[quantity],[discountPercent]
|
|
||||||
// 5. Attempt to convert values:
|
while (scanner.hasNextLine()) {
|
||||||
// - productId -> int
|
String line = scanner.nextLine();
|
||||||
// - quantity -> int
|
if (line.trim().isEmpty()) {
|
||||||
// - discountPercent -> int
|
continue;
|
||||||
// NOTE:
|
}
|
||||||
// - quantity and discountPercent may contain invalid characters
|
|
||||||
// (e.g., letters instead of numbers).
|
// استفاده از try-catch برای اینکه اگر خطایی در تبدیل متن به عدد رخ داد برنامه کرش نکند
|
||||||
// - If parsing any value fails (NumberFormatException),
|
try {
|
||||||
// the entire line must be considered invalid.
|
String[] parts = line.split(",");
|
||||||
// - Use try-catch blocks and exception handling to safely
|
|
||||||
// handle parsing and validation errors without stopping
|
// تبدیل متنها به اعداد صحیح و احتمال رخ دادن NumberFormatException
|
||||||
// the processing of the remaining lines.
|
int prodId = Integer.parseInt(parts[0].trim());
|
||||||
// 6. Validate parsed values:
|
int qty = Integer.parseInt(parts[1].trim());
|
||||||
// - productId must be greater than 0
|
int discPercent = Integer.parseInt(parts[2].trim());
|
||||||
// - quantity must be greater than 0
|
|
||||||
// - discountPercent must be between 0 and 99 inclusive
|
// شرطهای اعتبارسنجی: مقادیر نباید منفی باشند و درصد تخفیف نباید بیشتر از 100 باشد
|
||||||
// 7. Look for a Product in productList that matches productId
|
if (qty < 0 || discPercent < 0 || discPercent > 100) {
|
||||||
// 8. If no Product with that ID exists in the catalog,
|
totalInvalidLines++;
|
||||||
// the entire line is considered invalid
|
continue;
|
||||||
// 9. If all values are valid and the product exists, calculate:
|
}
|
||||||
// subtotal = quantity * product price
|
|
||||||
// discountValue = subtotal * discountPercent / 100
|
// گشتن توی لیست کاتالوگ برای پیدا کردن محصولی که این آیدی را دارد
|
||||||
// finalCost = subtotal - discountValue
|
Product foundProduct = null;
|
||||||
// 10. Update report totals:
|
for (int i = 0; i < productList.size(); i++) {
|
||||||
// - totalQuantity += quantity
|
if (productList.get(i).getProductID() == prodId) {
|
||||||
// - totalFinalCost += finalCost
|
foundProduct = productList.get(i);
|
||||||
// - totalDiscountValue += discountValue
|
break;
|
||||||
// 11. If any parsing error, validation failure, or missing product occurs:
|
}
|
||||||
// - increment totalInvalidLines
|
}
|
||||||
// - skip the line and continue processing the next line
|
|
||||||
// 12. Close all file resources
|
// اگر محصول توی کاتالوگ نبود خط نامعتبر حساب میشود
|
||||||
|
if (foundProduct == null) {
|
||||||
|
totalInvalidLines++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// فرمولهای محاسبات مالی طبق دستور کار پروژه
|
||||||
|
double subtotal = qty * foundProduct.getPrice();
|
||||||
|
double discountValue = (subtotal * discPercent) / 100.0;
|
||||||
|
double finalCost = subtotal - discountValue;
|
||||||
|
|
||||||
|
// جمع زدن مقادیر نهایی برای گزارش
|
||||||
|
totalQuantity += qty;
|
||||||
|
totalDiscountValue += discountValue;
|
||||||
|
totalFinalCost += finalCost;
|
||||||
|
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
// اگر توی متن حروف بود و تبدیل به عدد نشد، اینجا خطا رو میگیریم و خط رو نامعتبر میکنیم
|
||||||
|
totalInvalidLines++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// بستن فایل ورودی سفارشات
|
||||||
|
scanner.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void saveReport()
|
public void saveReport()
|
||||||
{
|
{
|
||||||
// TODO:
|
try {
|
||||||
// 1. Build a formatted report string
|
// ساختن فایل خروجی متنی جدید به نام report.txt
|
||||||
// 2. Include:
|
FileWriter fileWriter = new FileWriter("report.txt");
|
||||||
// - total quantity
|
PrintWriter printWriter = new PrintWriter(fileWriter);
|
||||||
// - 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 =========
|
printWriter.println("===== SALES REPORT =====");
|
||||||
Total Quantity Sold: 42
|
printWriter.println();
|
||||||
Total Final Cost: $1520.75
|
printWriter.println("Total Quantity: " + totalQuantity);
|
||||||
Total Discount Value: $230.50
|
printWriter.println("Total Final Cost: " + totalFinalCost);
|
||||||
Invalid Rows: 3
|
printWriter.println("Total Discount Value: " + totalDiscountValue);
|
||||||
================================
|
printWriter.println("Invalid Lines: " + totalInvalidLines);
|
||||||
*/
|
|
||||||
|
// بستن پرینتر و رایتر برای اعمال نهایی و ذخیره شدن اطلاعات در هارد
|
||||||
|
printWriter.close();
|
||||||
|
fileWriter.close();
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
// مدیریت خطای احتمالی موقع ساختن یا نوشتن در فایل
|
||||||
|
System.err.println("Error writing report file: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user