1 Commits
Author SHA1 Message Date
HesamGhazi a0b34a7b22 Implementation of WS-05 is completed 2026-06-21 19:38:15 +03:30
14 changed files with 268 additions and 85 deletions
Generated
+1
View File
@@ -0,0 +1 @@
Main.java
View File
+68 -44
View File
@@ -1,92 +1,116 @@
package org.Exceptions; package org.Exceptions;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Scanner; import java.util.Scanner;
import java.util.InputMismatchException;
/**
*
*
* @author Hesam Ghazi
* Student Number: 403222015
* @version 1.0
*/
public class FileService { public class FileService {
public static void main(String[] args) { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in);
System.out.println("Enter you first name: "); try {
System.out.println("Enter your first name: ");
String firstName = scanner.nextLine(); String firstName = scanner.nextLine();
System.out.println("Enter you last name: "); System.out.println("Enter your last name: ");
String lastName = scanner.nextLine(); String lastName = scanner.nextLine();
System.out.println("Enter your national code: "); System.out.println("Enter your national code: ");
Long nationalCode = scanner.nextLong(); Long nationalCode = scanner.nextLong();
scanner.nextLine(); scanner.nextLine(); // consume newline
System.out.println("Enter your email: "); System.out.println("Enter your email: ");
String email = scanner.nextLine(); String email = scanner.nextLine();
System.out.println("Enter your phone number: "); System.out.println("Enter your phone number: ");
Long phoneNumber = scanner.nextLong(); Long phoneNumber = scanner.nextLong();
scanner.nextLine(); scanner.nextLine(); // consume newline
System.out.println("Enter your dateOfBirth: "); System.out.println("Enter your dateOfBirth (yyyy-MM-dd): ");
String dateOfBirth = scanner.nextLine(); String dateOfBirth = scanner.nextLine();
UserEntity user = null; Date dob = parseDate(dateOfBirth);
if (dob == null) {
System.err.println("Registration aborted due to invalid date format.");
return;
}
user = new UserEntity(firstName, lastName, nationalCode, email, phoneNumber, parseDate(dateOfBirth)); UserEntity user = new UserEntity(firstName, lastName, nationalCode, email, phoneNumber, dob);
System.out.println("\nCreated User Info:");
System.out.println(user.toString()); System.out.println(user.toString());
System.out.println(writeFile(user)); System.out.println(writeFile(user));
System.out.println("\nReading top entries from file:");
readFile(); readFile();
} catch (InputMismatchException e) {
System.err.println("Input format error: Please enter valid numbers for numeric fields.");
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
} finally {
// Scanner should only be closed if it's the end of program usage
scanner.close();
}
} }
public static String writeFile(UserEntity user) { public static String writeFile(UserEntity user) {
//TODO: Uncomment the lines below. try (FileWriter fw = new FileWriter("userInformation.txt", true);
//TODO: Use your knowledge of exception handling to make the code work as expected BufferedWriter bw = new BufferedWriter(fw)) {
/* Uncomment this section
//TODO: handle the exception
FileWriter fw = new FileWriter("userInformation.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(user.toString()); bw.write(user.toString());
bw.close(); bw.newLine();
*/ return "User information written to file successfully";
return "user information written to file";
}
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
return "Failed to write user information to file";
}
}
public static void readFile() { public static void readFile() {
//TODO: Uncomment the lines below. try (FileReader file = new FileReader("userInformation.txt");
//TODO: Use your knowledge of exception handling to make the code work as expected BufferedReader fileInput = new BufferedReader(file)) {
/* Uncomment this section String line;
FileReader file = new FileReader("userInformation.txt"); int counter = 0;
while ((line = fileInput.readLine()) != null && counter < 3) {
BufferedReader fileInput = new BufferedReader(file); System.out.println(line);
counter++;
for (int counter = 0; counter < 3; counter++) }
System.out.println(fileInput.readLine()); if (counter == 0) {
System.out.println("The file is empty or no lines to read.");
fileInput.close(); }
*/ } catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
System.err.println("Please ensure userInformation.txt exists and has been created.");
} catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
}
} }
public static Date parseDate(String date) { public static Date parseDate(String date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
// Ensure parsing strictly follows pattern lengths (e.g. rejects 1990-15-55)
Date dob = null; formatter.setLenient(false);
try {
//TODO: Uncomment this line. return formatter.parse(date);
//TODO: Use your knowledge of exception handling to make the code work as expected } catch (ParseException e) {
//dob = formatter.parse(date); System.err.println("Error parsing date: " + e.getMessage());
System.err.println("Please use the format yyyy-MM-dd (e.g., 1990-01-15)");
return dob; return null;
}
} }
} }
+142 -1
View File
@@ -1,7 +1,148 @@
package org.Exceptions; package org.Exceptions;
import org.FileExamples.AddresesingModes.FileAddressing;
import org.FileExamples.CreatingFiles.CreateFileExample01;
import org.FileExamples.CreatingFiles.CreateFileExample02;
import org.FileExamples.DeletingFiles.DeleteFileExample01;
import org.FileExamples.DeletingFiles.DeleteFileExample02;
import org.FileExamples.ParsingJson.ParsingJsonExample01;
import org.FileExamples.ReadingFiles.ReadFileExample01;
import org.FileExamples.ReadingFiles.ReadFileExample02;
import org.FileExamples.WritingFiles.WriteFileExample01;
import org.FileExamples.WritingFiles.WriteFileExample02;
import java.util.Scanner;
/**
*
*
* @author Hesam Ghazi
* Student Number: 403222015
* @version 1.0
*/
public class Main { public class Main {
public static void main(String[] args) { static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
System.out.println("=====================================");
System.out.println(" Java Exceptions & File Handling");
System.out.println(" Workshop Demo");
System.out.println("=====================================\n");
while (!exit) {
System.out.println("Select an option:");
System.out.println("1. Run Exception Handling Demo (FileService)");
System.out.println("2. Run RuntimeException Demo");
System.out.println("3. File Addressing Demo");
System.out.println("4. Create File Examples");
System.out.println("5. Delete File Examples");
System.out.println("6. Read File Examples");
System.out.println("7. Write File Examples");
System.out.println("8. Parse JSON Example");
System.out.println("9. Exit");
System.out.print("\nEnter your choice (1-9): ");
try {
// Using nextLine() and parsing prevents scanner buffer bugs
String input = scanner.nextLine().trim();
int choice = Integer.parseInt(input);
System.out.println("\n-------------------------------------");
switch (choice) {
case 1:
System.out.println("Running FileService Demo...\n");
try {
FileService.main(new String[]{});
} catch (Exception e) {
System.err.println("Error in FileService: " + e.getMessage());
}
break;
case 2:
System.out.println("Running RuntimeException Demo...\n");
try {
RuntimeExceptionDemo.main(new String[]{});
} catch (Exception e) {
System.err.println("Expected exception caught: " + e.getClass().getSimpleName());
System.err.println("Message: " + e.getMessage());
}
break;
case 3:
System.out.println("Running File Addressing Demo...\n");
try {
FileAddressing.main();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
break;
case 4:
System.out.println("Running Create File Examples...\n");
System.out.println("Example 1 (File class):");
CreateFileExample01.main();
System.out.println("\nExample 2 (Files class):");
CreateFileExample02.main(new String[]{});
break;
case 5:
System.out.println("Running Delete File Examples...\n");
System.out.println("Example 1 (File class):");
DeleteFileExample01.main();
System.out.println("\nExample 2 (Files class):");
DeleteFileExample02.main();
break;
case 6:
System.out.println("Running Read File Examples...\n");
System.out.println("Example 1 (Scanner):");
ReadFileExample01.main();
System.out.println("\nExample 2 (Files.readAllLines):");
ReadFileExample02.main();
break;
case 7:
System.out.println("Running Write File Examples...\n");
System.out.println("Example 1 (FileWriter):");
WriteFileExample01.main();
System.out.println("\nExample 2 (Files.write):");
WriteFileExample02.main();
break;
case 8:
System.out.println("Running Parse JSON Example...\n");
try {
ParsingJsonExample01.main();
} catch (Exception e) {
System.err.println("Error parsing JSON: " + e.getMessage());
System.err.println("Make sure data.json is in the correct location.");
}
break;
case 9:
System.out.println("Exiting... Goodbye!");
exit = true;
break;
default:
System.out.println("Invalid choice. Please enter a number between 1 and 9.");
break;
}
if (!exit) {
System.out.println("-------------------------------------\n");
System.out.print("Press Enter to continue...");
scanner.nextLine();
}
} catch (NumberFormatException e) {
System.err.println("Invalid input. Please enter a valid menu number.");
System.out.println("-------------------------------------\n");
}
}
scanner.close();
} }
} }
@@ -8,20 +8,47 @@ public class RuntimeExceptionDemo {
UserEntity user = new UserEntity("Ali", "Ahmadi", 1234567890L, UserEntity user = new UserEntity("Ali", "Ahmadi", 1234567890L,
null, 989111111111L, null); null, 989111111111L, null);
// 1. Handle NullPointerException / IllegalArgumentException
try {
validateEmail(user); validateEmail(user);
calculatePayment(5000, 0); } catch (NullPointerException e) {
convertUserAge("twenty"); System.err.println("Caught NullPointerException: Email string cannot be null.");
completeRegistration(user); } catch (IllegalArgumentException e) {
System.err.println("Caught IllegalArgumentException: " + e.getMessage());
} }
// 2. Handle ArithmeticException
try {
calculatePayment(5000, 0);
} catch (ArithmeticException e) {
System.err.println("Caught ArithmeticException: Cannot divide payment by zero installments.");
}
// 3. Handle NumberFormatException
try {
convertUserAge("twenty");
} catch (NumberFormatException e) {
System.err.println("Caught NumberFormatException: Could not parse invalid age string.");
}
// 4. Handle IllegalStateException
try {
completeRegistration(user);
} catch (IllegalStateException e) {
System.err.println("Caught IllegalStateException: " + e.getMessage());
}
System.out.println("\nRuntimeExceptionDemo executed completely and safely!");
}
//nullPointerException
//IllegalArgumentException
public static void validateEmail(UserEntity user) { public static void validateEmail(UserEntity user) {
String email = user.getEmail(); String email = user.getEmail();
// Fix to prevent immediate NullPointerException before regex matching
if (email == null) {
throw new NullPointerException("Email cannot be null");
}
String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"; String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
if (!Pattern.matches(emailRegex, email)) { if (!Pattern.matches(emailRegex, email)) {
@@ -31,32 +58,22 @@ public class RuntimeExceptionDemo {
System.out.println("User email is valid"); System.out.println("User email is valid");
} }
// ArithmeticException
public static void calculatePayment(int totalAmount, int installmentCount) { public static void calculatePayment(int totalAmount, int installmentCount) {
int payment = totalAmount / installmentCount; int payment = totalAmount / installmentCount;
System.out.println("Each installment : " + payment); System.out.println("Each installment : " + payment);
} }
// NumberFormatException
public static void convertUserAge(String ageInput) { public static void convertUserAge(String ageInput) {
int age = Integer.parseInt(ageInput); int age = Integer.parseInt(ageInput);
System.out.println("User age: " + age); System.out.println("User age: " + age);
} }
// IllegalStateException
public static void completeRegistration(UserEntity user) { public static void completeRegistration(UserEntity user) {
if (user.getDateOfBirth() == null) { if (user.getDateOfBirth() == null) {
throw new IllegalStateException( throw new IllegalStateException(
"Registration cannot be completed. Date of birth is missing." "Registration cannot be completed. Date of birth is missing."
); );
} }
System.out.println("Registration completed"); System.out.println("Registration completed");
} }
} }
@@ -5,7 +5,7 @@ import java.nio.file.Path;
import java.util.Scanner; import java.util.Scanner;
public class FileAddressing { public class FileAddressing {
static void main() { public static void main() {
//relative //relative
Path relativePath = Path.of("data.txt"); Path relativePath = Path.of("data.txt");
//absolute //absolute
@@ -4,7 +4,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
public class CreateFileExample01 { public class CreateFileExample01 {
static void main() { public static void main() {
File file = new File("texts/examples.txt"); File file = new File("texts/examples.txt");
try try
{ {
@@ -3,7 +3,7 @@ package org.FileExamples.DeletingFiles;
import java.io.File; import java.io.File;
public class DeleteFileExample01 { public class DeleteFileExample01 {
static void main() { public static void main() {
File file = new File("example.txt"); File file = new File("example.txt");
if (file.delete()) { if (file.delete()) {
@@ -5,7 +5,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
public class DeleteFileExample02 { public class DeleteFileExample02 {
static void main() { public static void main() {
try try
{ {
Path path = Path.of("example.txt"); Path path = Path.of("example.txt");
@@ -12,7 +12,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ParsingJsonExample01 { public class ParsingJsonExample01 {
static void main() { public static void main() {
try { try {
Path path = Path.of("data.json"); Path path = Path.of("data.json");
@@ -5,7 +5,7 @@ import java.io.FileNotFoundException;
import java.util.Scanner; import java.util.Scanner;
public class ReadFileExample01 { public class ReadFileExample01 {
static void main() { public static void main() {
File file = new File("quotes.txt"); File file = new File("quotes.txt");
try { try {
Scanner reader = new Scanner(file); Scanner reader = new Scanner(file);
@@ -6,7 +6,7 @@ import java.nio.file.Path;
import java.util.List; import java.util.List;
public class ReadFileExample02 { public class ReadFileExample02 {
static void main() { public static void main() {
Path path = Path.of("quotes.txt"); Path path = Path.of("quotes.txt");
try { try {
List<String> lines = Files.readAllLines(path); List<String> lines = Files.readAllLines(path);
@@ -4,7 +4,7 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
public class WriteFileExample01 { public class WriteFileExample01 {
static void main() { public static void main() {
try try
{ {
@@ -10,7 +10,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class WriteFileExample02 { public class WriteFileExample02 {
static void main() { public static void main() {
List<String> lines = List.of( List<String> lines = List.of(
"Line 1", "Line 1",
"Line 2" "Line 2"