Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0b34a7b22 |
Generated
+1
@@ -0,0 +1 @@
|
||||
Main.java
|
||||
@@ -1,92 +1,116 @@
|
||||
package org.Exceptions;
|
||||
|
||||
import java.io.*;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Scanner;
|
||||
import java.util.InputMismatchException;
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author Hesam Ghazi
|
||||
* Student Number: 403222015
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
public class FileService {
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.println("Enter you first name: ");
|
||||
String firstName = scanner.nextLine();
|
||||
try {
|
||||
System.out.println("Enter your first name: ");
|
||||
String firstName = scanner.nextLine();
|
||||
|
||||
System.out.println("Enter you last name: ");
|
||||
String lastName = scanner.nextLine();
|
||||
System.out.println("Enter your last name: ");
|
||||
String lastName = scanner.nextLine();
|
||||
|
||||
System.out.println("Enter your national code: ");
|
||||
Long nationalCode = scanner.nextLong();
|
||||
scanner.nextLine();
|
||||
System.out.println("Enter your national code: ");
|
||||
Long nationalCode = scanner.nextLong();
|
||||
scanner.nextLine(); // consume newline
|
||||
|
||||
System.out.println("Enter your email: ");
|
||||
String email = scanner.nextLine();
|
||||
System.out.println("Enter your email: ");
|
||||
String email = scanner.nextLine();
|
||||
|
||||
System.out.println("Enter your phone number: ");
|
||||
Long phoneNumber = scanner.nextLong();
|
||||
scanner.nextLine();
|
||||
System.out.println("Enter your phone number: ");
|
||||
Long phoneNumber = scanner.nextLong();
|
||||
scanner.nextLine(); // consume newline
|
||||
|
||||
System.out.println("Enter your dateOfBirth: ");
|
||||
String dateOfBirth = scanner.nextLine();
|
||||
System.out.println("Enter your dateOfBirth (yyyy-MM-dd): ");
|
||||
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(user.toString());
|
||||
System.out.println("\nCreated User Info:");
|
||||
System.out.println(user.toString());
|
||||
|
||||
System.out.println(writeFile(user));
|
||||
readFile();
|
||||
System.out.println(writeFile(user));
|
||||
|
||||
System.out.println("\nReading top entries from file:");
|
||||
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) {
|
||||
//TODO: Uncomment the lines below.
|
||||
//TODO: Use your knowledge of exception handling to make the code work as expected
|
||||
try (FileWriter fw = new FileWriter("userInformation.txt", true);
|
||||
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.newLine();
|
||||
return "User information written to file successfully";
|
||||
|
||||
bw.write(user.toString());
|
||||
bw.close();
|
||||
*/
|
||||
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() {
|
||||
//TODO: Uncomment the lines below.
|
||||
//TODO: Use your knowledge of exception handling to make the code work as expected
|
||||
try (FileReader file = new FileReader("userInformation.txt");
|
||||
BufferedReader fileInput = new BufferedReader(file)) {
|
||||
|
||||
/* Uncomment this section
|
||||
FileReader file = new FileReader("userInformation.txt");
|
||||
|
||||
BufferedReader fileInput = new BufferedReader(file);
|
||||
|
||||
for (int counter = 0; counter < 3; counter++)
|
||||
System.out.println(fileInput.readLine());
|
||||
|
||||
fileInput.close();
|
||||
*/
|
||||
String line;
|
||||
int counter = 0;
|
||||
while ((line = fileInput.readLine()) != null && counter < 3) {
|
||||
System.out.println(line);
|
||||
counter++;
|
||||
}
|
||||
if (counter == 0) {
|
||||
System.out.println("The file is empty or no lines to read.");
|
||||
}
|
||||
} 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) {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
|
||||
Date dob = null;
|
||||
|
||||
//TODO: Uncomment this line.
|
||||
//TODO: Use your knowledge of exception handling to make the code work as expected
|
||||
//dob = formatter.parse(date);
|
||||
|
||||
return dob;
|
||||
// Ensure parsing strictly follows pattern lengths (e.g. rejects 1990-15-55)
|
||||
formatter.setLenient(false);
|
||||
try {
|
||||
return formatter.parse(date);
|
||||
} catch (ParseException e) {
|
||||
System.err.println("Error parsing date: " + e.getMessage());
|
||||
System.err.println("Please use the format yyyy-MM-dd (e.g., 1990-01-15)");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,148 @@
|
||||
|
||||
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 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,
|
||||
null, 989111111111L, null);
|
||||
|
||||
validateEmail(user);
|
||||
calculatePayment(5000, 0);
|
||||
convertUserAge("twenty");
|
||||
completeRegistration(user);
|
||||
// 1. Handle NullPointerException / IllegalArgumentException
|
||||
try {
|
||||
validateEmail(user);
|
||||
} catch (NullPointerException e) {
|
||||
System.err.println("Caught NullPointerException: Email string cannot be null.");
|
||||
} 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) {
|
||||
|
||||
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.-]+$";
|
||||
|
||||
if (!Pattern.matches(emailRegex, email)) {
|
||||
@@ -31,32 +58,22 @@ public class RuntimeExceptionDemo {
|
||||
System.out.println("User email is valid");
|
||||
}
|
||||
|
||||
// ArithmeticException
|
||||
public static void calculatePayment(int totalAmount, int installmentCount) {
|
||||
|
||||
int payment = totalAmount / installmentCount;
|
||||
|
||||
System.out.println("Each installment : " + payment);
|
||||
}
|
||||
|
||||
// NumberFormatException
|
||||
public static void convertUserAge(String ageInput) {
|
||||
|
||||
int age = Integer.parseInt(ageInput);
|
||||
|
||||
System.out.println("User age: " + age);
|
||||
}
|
||||
|
||||
// IllegalStateException
|
||||
public static void completeRegistration(UserEntity user) {
|
||||
|
||||
if (user.getDateOfBirth() == null) {
|
||||
throw new IllegalStateException(
|
||||
"Registration cannot be completed. Date of birth is missing."
|
||||
);
|
||||
}
|
||||
|
||||
System.out.println("Registration completed");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import java.nio.file.Path;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileAddressing {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
//relative
|
||||
Path relativePath = Path.of("data.txt");
|
||||
//absolute
|
||||
|
||||
@@ -4,7 +4,7 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class CreateFileExample01 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
File file = new File("texts/examples.txt");
|
||||
try
|
||||
{
|
||||
|
||||
@@ -3,7 +3,7 @@ package org.FileExamples.DeletingFiles;
|
||||
import java.io.File;
|
||||
|
||||
public class DeleteFileExample01 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
File file = new File("example.txt");
|
||||
|
||||
if (file.delete()) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class DeleteFileExample02 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
try
|
||||
{
|
||||
Path path = Path.of("example.txt");
|
||||
|
||||
@@ -12,7 +12,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ParsingJsonExample01 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
|
||||
try {
|
||||
Path path = Path.of("data.json");
|
||||
|
||||
@@ -5,7 +5,7 @@ import java.io.FileNotFoundException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class ReadFileExample01 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
File file = new File("quotes.txt");
|
||||
try {
|
||||
Scanner reader = new Scanner(file);
|
||||
|
||||
@@ -6,7 +6,7 @@ import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
public class ReadFileExample02 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
Path path = Path.of("quotes.txt");
|
||||
try {
|
||||
List<String> lines = Files.readAllLines(path);
|
||||
|
||||
@@ -4,7 +4,7 @@ import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
public class WriteFileExample01 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@@ -10,7 +10,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class WriteFileExample02 {
|
||||
static void main() {
|
||||
public static void main() {
|
||||
List<String> lines = List.of(
|
||||
"Line 1",
|
||||
"Line 2"
|
||||
|
||||
Reference in New Issue
Block a user