Jumat, 16 Desember 2016

OOP dalam ATM

ATM menurut Ellen Florian (2004) adalah ”alat telekomunikasi berbasis komputer yang menyediakan tempat bagi nasabah dalam melakukan transaksi keuangan tanpa membutuhkan seorang teller bank.”. ATM dalam bahasa asing Automated Teller Machine dan dalam bahasa Indonesia Anjungan Tunai Mandiri.

Secara umum fungsi ATM adalah agar dapat melakukan penarikan uang tunai, namun selain itu masih banyak fungsi ATM yang dapat mempermudah kepentingan kita sebagai nasabah.

Pengimplementasiannya sebagai berikut : (Klik Read More)
Source codenya (created by Format My SourceCode for Blogging) :
//class CaseATMStudy

public class ATMCaseStudy
{
 /**
 * Constructor for objects of class ATMCaseStudy
 */
 public ATMCaseStudy()
 {
 
 }

 public static void main(String[] args)
 {
 ATM theATM = new ATM();
 theATM.run();
 }
}

//class ATM

public class ATM
{
 private boolean userAuthenticated;
 private int currentAccountNumber;
 private Screen screen;
 private Keypad keypad;
 private CashDispenser cashDispenser;
 private DepositSlot depositSlot;
 private BankDatabase bankDatabase;
 
 private static final int BALANCE_INQUIRY = 1;
 private static final int WITHDRAWL = 2;
 private static final int DEPOSIT = 3;
 private static final int EXIT = 4;

 /**
 * Constructor for objects of class ATM
 */
 public ATM()
 {
 userAuthenticated = false;
 currentAccountNumber = 0;
 screen = new Screen();
 keypad = new Keypad();
 cashDispenser = new CashDispenser();
 depositSlot = new DepositSlot();
 bankDatabase = new BankDatabase();
 }

 public void run()
 {
 while(true)
 {
 while(!userAuthenticated)
 {
 screen.displayMessageLine("\nWelcome!");
 authenticateUser();
 }
 
 performTransactions();
 userAuthenticated = false;
 currentAccountNumber = 0;
 screen.displayMessageLine("\nThank you! Goodbye!");
 }
 }
 
 private void authenticateUser()
 {
 screen.displayMessage("\nPlease enter your account number: ");
 int accountNumber = keypad.getInput();
 screen.displayMessage("\nEnter your PIN: ");
 int pin = keypad.getInput();
 
 userAuthenticated = bankDatabase.authenticateUser(accountNumber, pin);
 
 if(userAuthenticated)
 {
 currentAccountNumber = accountNumber;
 }
 else
 screen.displayMessageLine("Invalid account number or PIN. Please try again.");
 }
 
 private void performTransactions()
 {
 Transaction currentTransaction = null;
 boolean userExited = false;
 
 while(!userExited)
 {
 int mainMenuSelection = displayMainMenu();
 
 switch(mainMenuSelection)
 {
 case BALANCE_INQUIRY:
 case WITHDRAWL:
 case DEPOSIT:
 currentTransaction = createTransaction(mainMenuSelection);
 currentTransaction.execute();
 break;
 case EXIT:
 screen.displayMessageLine("\nExiting the system...");
 userExited = true;
 break;
 default:
 screen.displayMessageLine("\nYou did not enter a valid selection. Tr again.");
 break;
 }
 }
 }
 
 private int displayMainMenu()
 {
 screen.displayMessageLine("\nMain menu:");
 screen.displayMessageLine("1 - View my balance");
 screen.displayMessageLine("2 - Withdraw cash");
 screen.displayMessageLine("3 - Deposit funds");
 screen.displayMessageLine("4 - Exit\n");
 screen.displayMessage("Enter a choice: ");
 return keypad.getInput();
 }
 
 private Transaction createTransaction(int type)
 {
 Transaction temp = null;
 
 switch(type)
 {
 case BALANCE_INQUIRY:
 temp = new BalanceInquiry(currentAccountNumber, screen, bankDatabase);
 break;
 case WITHDRAWL:
 temp = new Deposit(currentAccountNumber, screen, bankDatabase, keypad, depositSlot);
 break;
 }
 
 return temp;
 }
}

//class Keypad

public class Keypad
{
 private Scanner input;
 
 /**
 * Constructor for objects of class Keypad
 */
 public Keypad()
 {
 input = new Scanner(System.in);
 }
 
 public int getInput()
 {
 return input.nextInt();
 }
}

//class DepositSlot

public class DepositSlot
{
 /**
 * Constructor for objects of class DepositSlot
 */
 public DepositSlot()
 {
 
 }

 public boolean isEnvelopeReceived()
 {
 return true;
 }
}

//class CashDispenser

public class CashDispenser
{
 private final static int INITIAL_COUNT = 500;
 private int count;
 
 /**
 * Constructor for objects of class CashDispenser
 */
 public CashDispenser()
 {
 count = INITIAL_COUNT;
 }

 public void dispenseCash(int amount)
 {
 int billsRequired = amount/20;
 count -= billsRequired;
 }
 
 public boolean isSufficientCashAvailable(int amount)
 {
 int billsRequired = amount/20;
 if(count>=billsRequired)
 return true;
 else
 return false;
 }
}

//class Screen

public class Screen
{
 /**
 * Constructor for objects of class Screen
 */
 public Screen()
 {
 
 }

 public void displayMessage(String message)
 {
 System.out.print(message);
 }
 
 public void displayMessageLine(String message)
 {
 System.out.println(message);
 }
 
 public void displayDollarAmount(double amount)
 {
 System.out.printf("$%,.2f", amount);
 }
}

//class Deposit

public class Deposit extends Transaction
{
 private double amount;
 private Keypad keypad;
 private DepositSlot depositSlot;
 private final static int CANCELED = 0;

 /**
 * Constructor for objects of class Deposit
 */
 public Deposit(int userAccountNumber, Screen atmScreen, BankDatabase atmBankDatabase, Keypad atmKeypad, DepositSlot atmDepositSlot)
 {
 super(userAccountNumber, atmScreen, atmBankDatabase);
 
 keypad = atmKeypad;
 depositSlot = atmDepositSlot;
 }

 public void execute()
 {
 BankDatabase bankDatabase = getBankDatabase();
 Screen screen = getScreen();
 amount = promptForDepositAmount();
 
 if(amount != CANCELED)
 {
 screen.displayMessage("\nPlease insert a deposit envelope containing ");
 screen.displayDollarAmount( amount );
 screen.displayMessageLine( "." );
 
 boolean envelopeReceived = depositSlot.isEnvelopeReceived();
 
 if(envelopeReceived)
 {
 screen.displayMessageLine("\nYour envelope has been " + "received.\nNOTE: The money just deposited will not " + "be available until we verify the amount of any " + "enclosed cash and your checks clear.");
 bankDatabase.credit(getAccountNumber(), amount);
 }
 
 else
 {
 screen.displayMessageLine( "\nYou did not insert an " + "envelope, so the ATM has canceled your transaction." );
 }
 }
 
 else
 {
 screen.displayMessageLine( "\nCanceling transaction..." );
 }
 }
 
 private double promptForDepositAmount()
 {
 Screen screen = getScreen();
 
 screen.displayMessage( "\nPlease enter a deposit amount in " + "CENTS (or 0 to cancel): " );
 
 int input = keypad.getInput();
 
 if ( input == CANCELED )
 return CANCELED;
 else
 {
 return (double)input/100;
 }
 }
}

//class Transaction

public abstract class Transaction
{
 private int accountNumber;
 private Screen screen;
 private BankDatabase bankDatabase;

 /**
 * Constructor for objects of class Transaction
 */
 public Transaction(int userAccountNumber, Screen atmScreen, BankDatabase atmBankDatabase)
 {
 accountNumber = userAccountNumber;
 screen = atmScreen;
 bankDatabase = atmBankDatabase;
 }

 public int getAccountNumber()
 {
 return accountNumber;
 }
 
 public Screen getScreen()
 {
 return screen;
 }
 
 public BankDatabase getBankDatabase()
 {
 return bankDatabase;
 }
 
 abstract public void execute();
}

//class Withdrawal

public class Withdrawal extends Transaction
{
 private int amount;
 private Keypad keypad;
 private CashDispenser cashDispenser;
 
 private final static int CANCELED = 6;
 
 /**
 * Constructor for objects of class Withdrawal
 */
 public Withdrawal(int userAccountNumber, Screen atmScreen, BankDatabase atmBankDatabase, Keypad atmKeypad, CashDispenser atmCashDispenser)
 {
 super( userAccountNumber, atmScreen, atmBankDatabase );
 
 keypad = atmKeypad;
 cashDispenser = atmCashDispenser;
 }

 public void execute()
 {
 boolean cashDispensed = false;
 double availableBalance;
 
 BankDatabase bankDatabase = getBankDatabase();
 Screen screen = getScreen();
 
 do
 {
 amount = displayMenuOfAmounts();
 
 if(amount != CANCELED)
 {
 availableBalance = bankDatabase.getAvailableBalance(getAccountNumber());
 
 if(amount <= availableBalance)
 {
 if(cashDispenser.isSufficientCashAvailable( amount ) )
 {
 bankDatabase.debit(getAccountNumber(), amount);
 cashDispenser.dispenseCash(amount);
 cashDispensed= true;
 
 screen.displayMessageLine("\nYour cash has been" + " dispensed. Please take your cash now.");
 }
 
 else
 {
 screen.displayMessageLine("\nInsufficient cash available in the ATM." + "\n\nPlease choose a smaller amount.");
 }
 }
 
 else
 {
 screen.displayMessageLine("\nInsufficient funds in your account." + "\n\nPlease choose a smaller amount.");
 }
 }
 
 else
 {
 screen.displayMessageLine( "\nCanceling transaction..." );
 return;
 }
 }while (!cashDispensed);
 }
 
 private int displayMenuOfAmounts()
 {
 int userChoice = 0;
 Screen screen = getScreen();
 int[] amounts = {0,20,40,60,100,200};
 
 while(userChoice == 0)
 {
 screen.displayMessageLine( "\nWithdrawal Menu:" );
 screen.displayMessageLine( "1 - $20" );
 screen.displayMessageLine( "2 - $40" );
 screen.displayMessageLine( "3 - $60" );
 screen.displayMessageLine( "4 - $100" );
 screen.displayMessageLine( "5 - $200" );
 screen.displayMessageLine( "6 - Cancel transaction" );
 screen.displayMessage( "\nChoose a withdrawal amount: " );
 
 int input = keypad.getInput();
 
 switch(input)
 {
 case 1:
 case 2:
 case 3:
 case 4:
 case 5:
 userChoice = amounts[input];
 break;
 case CANCELED:
 userChoice = CANCELED;
 break;
 default:
 screen.displayMessageLine("\nInvalid selection. Try again.");
 }
 }
 
 return userChoice;
 }
}

//class BalanceInquiry

public class BalanceInquiry extends Transaction
{
 /**
 * Constructor for objects of class BalanceInquiry
 */
 public BalanceInquiry(int userAccountNumber, Screen atmScreen, BankDatabase atmBankDatabase)
 {
 super(userAccountNumber, atmScreen, atmBankDatabase);
 }

 public void execute()
 {
 BankDatabase bankDatabase = getBankDatabase();
 Screen screen = getScreen();
 
 double availableBalance = bankDatabase.getAvailableBalance(getAccountNumber());
 
 double totalBalance = bankDatabase.getTotalBalance(getAccountNumber());
 
 screen.displayMessageLine( "\nBalance Information:" );
 screen.displayMessage( " - Available balance: " );
 screen.displayDollarAmount( availableBalance );
 screen.displayMessage( "\n - Total balance: " );
 screen.displayDollarAmount( totalBalance );
 screen.displayMessageLine( "" );
 }
}

//class BankDatabase

public class BankDatabase
{
 private Account[] accounts;

 /**
 * Constructor for objects of class BankDatabase
 */
 public BankDatabase()
 {
 accounts = new Account[2];
 accounts[0] = new Account(12345, 54321, 1000.0, 1200.0);
 accounts[1] = new Account(98765, 56789, 200.0, 200.0);
 }

 private Account getAccount(int accountNumber)
 {
 for(Account currentAccount : accounts)
 {
 if(currentAccount.getAccountNumber() == accountNumber)
 return currentAccount;
 }
 
 return null;
 }
 
 public boolean authenticateUser(int userAccountNumber, int userPIN)
 {
 Account userAccount = getAccount(userAccountNumber);
 
 if(userAccount != null)
 return userAccount.validatePIN(userPIN);
 else
 return false;
 }
 
 public double getAvailableBalance(int userAccountNumber)
 {
 return getAccount(userAccountNumber).getAvailableBalance();
 }
 
 public double getTotalBalance(int userAccountNumber)
 {
 return getAccount(userAccountNumber).getTotalBalance();
 }
 
 public void credit(int userAccountNumber, double amount)
 {
 getAccount(userAccountNumber).credit(amount);
 }
 
 public void debit(int userAccountNumber, double amount)
 {
 getAccount(userAccountNumber).debit(amount);
 }
}

//class Account

public class Account
{
 private int accountNumber;
 private int pin;
 private double availableBalance;
 private double totalBalance;

 /**
 * Constructor for objects of class Account
 */
 public Account(int theAccountNumber, int thePIN, double theAvailableBalance, double theTotalBalance)
 {
 accountNumber = theAccountNumber;
 pin = thePIN;
 availableBalance = theAvailableBalance;
 totalBalance = theTotalBalance;
 }

 public boolean validatePIN(int userPIN)
 {
 if (userPIN == pin)
 return true;
 else 
 return false;
 }
 
 public double getAvailableBalance()
 {
 return availableBalance;
 }
 
 public double getTotalBalance()
 {
 return totalBalance;
 }
 
 public void credit(double amount)
 {
 totalBalance += amount;
 }
 
 public void debit(double amount)
 {
 availableBalance -= amount;
 totalBalance -= amount;
 }
 
 public int getAccountNumber()
 {
 return accountNumber;
 }
}

Berikut hasilnya setelah di run : 


Read More..

Kamis, 17 November 2016

Menggunakan Library

Hai bertemu saya lagi :) Kali ini saya akan membahas Pemrograman Berorientasi Objek menggunakan Java mengenai menggunakan Library.

Pertama-tama apa sih Library itu ?
Library adalah sekumpulan package atau koleksi kelas yang telah disediakan oleh Java. Untuk menggunakan Library dalam java kita menggunakan syntax import.

Biar tidak bingung langsung saja ya kita implementasikan.
Latihan Luas & Keliling Persegi Panjang

Source codenya (created by Format My SourceCode for Blogging) :

import java.util.Scanner;
public class Latihan_java {


    public static void main(String[] args) 
    {
        int panjang, lebar, hasil;
        String karakter;
        
        hasil = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Program Penghitung Luas dan Keliling Persegi panjang");
        System.out.print("Masukan Panjang Persegi: ");
        panjang = sc.nextInt();
        
        System.out.print("Masukan Lebar Persegi: ");
        lebar = sc.nextInt();
        
        System.out.println("Tekan (L) untuk melihat Luas");
        System.out.print("Tekan (K) untuk melihat keliling: ");
        karakter = sc.next();
        switch(karakter)
        {
            case "L":
                hasil = panjang * lebar;
                break;
                
            case "K":
                hasil = 2 * (panjang + lebar);
                break;
                
            default:
                System.out.print("Anda salah memasukan inputan");
                break;
        }
        sc.close();
        System.out.print("Hasilnya adalah: " + hasil);
        System.out.println();
    }
    
}

Dan setelah dicompile, kita isi Panjang dan Lebar, maka :

Read More..

Overloading dan Overriding

Hi :) selamat pagi semua ! Bagaimana kabarnya hari ini? Alhamdulillah saya pribadi diberi kesehatan sehingga bisa menjalani aktivitas seperti biasa.

Pada kesempatan kali ini saya ingin mengupload tugas PBO saya sekaligus menjelaskannya secara keseluruhan.

Materi pada kesempatan kali ini yaitu mengenai "Overloading dan Overriding."
Apa itu Overloading dan Overriding?

Well, pada dasarnya Overloading dan Overriding adalah merupakan sebuah method-method. Method-method apakah itu?


Method Overloading adalah sebuah kemampuan yang membolehkan sebuah class mempunyai 2 atau lebih method dengan nama yang sama, yang membedakan adalah parameternya.

Sedangkan method overriding merupakan method yang parrent class ditulis kembali oleh subclass.

Biar tidak bingung langsung implementasinya saja ya hehehe.

Overloading 
Saya buat dua kelas, MyClass dan Main_Class

Source codenya (created by Format My SourceCode for Blogging) :

public class MyClass
{
    int height;
    MyClass(){
        System.out.println("bricks");
        height = 0;
    }
   
    MyClass(int i){
        System.out.println("Building a new house that is " + i + " feet tall");
        height = i;
    }
   
    void info(){
        System.out.println("House is " + height + " feet tall");
    }
   
    void info(String s){
        System.out.println(s + " : House is " + height + " feet tall");
    }
}

public class Main_Class
{
    public static void main(String[] args){
        MyClass t = new MyClass(2);
        t.info();
        t.info("overloaded method");
        // Overload Constructor:
        new MyClass();
    }
}



Relasinya sebagai berikut :


Lalu setelah dijalankan programnya, akan menghasilkan sbb :

Lalu yang kedua mengenai implementasi Overriding.
Saya membuat tiga kelas, yaitu Kelas 1 (Binatang), Kelas 2 (Mamalia) dan Kelas 3 (Main Classnya)

Source codenya (created by Format My SourceCode for Blogging) :

public class Binatang {
    public void begerak(){
        System.out.println("Binatang bergerak sesuai kemampuannya");
    }
    public void berkembangBiak(){
        System.out.println("Binatang berkembang biak sesuai kemampuannya");
    }

}
public class Mamalia extends Binatang {
    //overriding method parent class
    public void begerak(){
        System.out.println("Mamalia bergerak sebagian besar dengan kakinya");
    }    
    public void berlari(){
        System.out.println("Sebagian Mamalia dapat berlari");
    }
}
public class PenggunaanOverriding {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Binatang b = new Binatang();
        Mamalia m = new Mamalia();
        Binatang bm = new Mamalia();
        
        b.begerak();
        m.begerak();
        bm.begerak();
        bm.berkembangBiak();
    }
}
 
  

Relasinya :
Dan setelah dicompile, akan menghasilkan sbb :

Read More..
Related Posts Plugin for WordPress, Blogger...