Skip to content

Instantly share code, notes, and snippets.

@hoangvvo
Last active September 27, 2023 07:57
Show Gist options
  • Save hoangvvo/5c81da3d6ec6ee9b9587928f0f521f79 to your computer and use it in GitHub Desktop.
Save hoangvvo/5c81da3d6ec6ee9b9587928f0f521f79 to your computer and use it in GitHub Desktop.
CO3001_OOP class exercise
#include <iostream>
#include <string>
#include <exception>
using namespace std;
class BankAccount
{
private:
int accountNumber;
string accountHolderName;
double balance;
public:
BankAccount(int accountNumber, string accountHolderName, double balance)
{
this->accountNumber = accountNumber;
this->accountHolderName = accountHolderName;
this->balance = balance;
}
void deposit(double amount)
{
if (amount <= 0)
{
cout << "Amount must be greater than 0" << endl;
return;
}
balance += amount;
cout << "You have deposited " << amount << " to your account. New balance: " << balance << endl;
}
void withdraw(double amount)
{
if (amount <= 0)
{
cout << "Amount must be greater than 0" << endl;
return;
}
if (balance - amount < 0)
{
cout << "Insufficient balance" << endl;
}
else
{
balance -= amount;
cout << "You have withdrawn " << amount << " from your account. Remaining balance: " << balance << endl;
}
}
void checkBalance()
{
cout << "Balance: " << balance << endl;
}
};
int main() {
int accountNumber;
string accountHolderName;
double balance;
try {
cout << "Enter account number: ";
cin >> accountNumber;
cout << "Enter account holder name: ";
cin >> accountHolderName;
cout << "Enter initial balance: ";
cin >> balance;
if (balance <= 0) {
throw exception();
}
} catch (exception e) {
cout << "Invalid input" << endl;
exit(1);
}
BankAccount bankAccount(accountNumber, accountHolderName, balance);
int option;
double amount;
while (true)
{
cout << "1. Deposit" << endl;
cout << "2. Withdraw" << endl;
cout << "3. Check balance" << endl;
cout << "4. Exit" << endl;
cout << "Enter option: ";
cin >> option;
try {
switch (option)
{
case 1:
cout << "Enter amount to deposit: ";
cin >> amount;
bankAccount.deposit(amount);
break;
case 2:
cout << "Enter amount to withdraw: ";
cin >> amount;
bankAccount.withdraw(amount);
break;
case 3:
bankAccount.checkBalance();
break;
case 4:
exit(0);
default:
cout << "Invalid option" << endl;
break;
}
} catch (exception e) {
cout << "Invalid input" << endl;
exit(1);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment