Untitled
unknown
plain_text
2 years ago
2.7 kB
9
Indexable
class InsufficientFundsException extends Exception {
public InsufficientFundsException(double balance, double withdrawalAmount) {
super("Insufficient funds. Current balance: $" + balance + ", tried to withdraw: $" + withdrawalAmount);
}
}
class BankAccount {
private int accountNumber;
private double balance;
private String accountHolder;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(balance, amount);
}
balance -= amount;
}
}
public class BankAccountExample {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0);
try {
account.withdraw(1500.0);
} catch (InsufficientFundsException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.*;
import java.io.Serializable;
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class SerializationDeserializationExample {
public static void main(String[] args) {
// Create a Person object
Person person = new Person("Alice", 30);
// Serialize the Person object to a file
serializePerson(person);
// Deserialize the Person object from the file and print its information
Person deserializedPerson = deserializePerson();
if (deserializedPerson != null) {
System.out.println("Deserialized Person: Name: " + deserializedPerson.getName() + ", Age: " + deserializedPerson.getAge());
}
}
public static void serializePerson(Person person) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
System.out.println("Person object has been serialized.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static Person deserializePerson() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
return (Person) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
Editor is loading...