@Test public void testGetCash() throws NotEnoughMoneyInAccountException, NotEnoughMoneyInATMException, NoCardInsertedException { System.out.println("getCashNotZeroBalance"); double atmMoney = 1000.0; ATM atmTest = new ATM(atmMoney); Card mockCard = mock(Card.class); Account mockAccount = mock(Account.class); atmTest.insertCard(mockCard); // ver.2 double balance = 600.0; double amount = 100.0; int pinCode = 7777; when(mockCard.getAccount()).thenReturn(mockAccount); when(mockCard.checkPin(pinCode)).thenReturn(true); when(mockCard.isBlocked()).thenReturn(false); when(mockAccount.getBalance()).thenReturn(balance); when(mockAccount.withdrow(amount)).thenReturn(amount); atmTest.validateCard(mockCard, pinCode); atmTest.getCash(amount); when(mockAccount.getBalance()).thenReturn(balance - amount); assertEquals(atmTest.getMoneyInATM(), atmMoney - amount, 0.0); assertEquals(atmTest.checkBalance(), balance - amount, 0.0); InOrder inOrder = inOrder(mockCard, mockAccount); inOrder.verify(mockCard).isBlocked(); inOrder.verify(mockCard).checkPin(pinCode); inOrder.verify(mockCard, atLeastOnce()).getAccount(); verify(mockAccount).withdrow(amount); inOrder.verify(mockAccount).getBalance(); }
public static void main(String args[]) { Account myAccount = new Account(); Account yourAccount = new Account(); myAccount.setName("Barry Burd"); myAccount.setAddress("222 Cyberspace Lane"); myAccount.setBalance(24.02); yourAccount.setName("Jane Q. Public"); yourAccount.setAddress("111 Consumer Street"); yourAccount.setBalance(55.63); out.print(myAccount.getName()); out.print(" ("); out.print(myAccount.getAddress()); out.print(") has $"); out.print(myAccount.getBalance()); out.println(); out.print(yourAccount.getName()); out.print(" ("); out.print(yourAccount.getAddress()); out.print(") has $"); out.print(yourAccount.getBalance()); }
public static void main(String[] args) { Person p = new Person("John", "Jones"); System.out.println(p.getFirstName()); System.out.println(p.getLastName()); Account acct = new Account(p, 1); acct.deposit(100); System.out.println(acct.getBalance()); acct.deposit(45.50); System.out.println(acct.getBalance()); if (acct.withdraw(95)) { System.out.println("New Balance is " + acct.getBalance()); } else { System.out.println("insufficent funds"); } if (acct.withdraw(100)) { System.out.println("New Balance is " + acct.getBalance()); } else { System.out.println("insufficent funds"); } System.out.println("Owner is: " + acct.getOwnersName()); System.out.println("Account number is: " + acct.getAcctNumber()); System.out.println("Transaction History: " + acct.getTransactions()); }
/** * @param amount * @param source * @param target */ public static void transfer(double amount, Account source, Account target) { if (source.getBalance() < amount) { System.out.println(source.getBalance() + " " + amount); throw new IllegalStateException(); } source.debit(amount); target.credit(amount); }
public void withdrawAmount(String name, long amount) throws AmountExceedsAccountBalanceException { Account account = accountRepository.findOne(name); Long newBalance = account.getBalance() - amount; if (newBalance < 0) { throw new AmountExceedsAccountBalanceException("You Can't Exceed Your Current Balance"); } else { account.setBalance(newBalance); accountRepository.save(account); transactionService.createTransaction(name, "Withdraw", "", amount, account.getBalance()); } }
public boolean withDraw(Account account, int amount) { boolean moneyWithdrawn = false; if (account.getBalance() >= amount) { account.withdraw(amount); moneyWithdrawn = true; System.out.println( "Please collect your cash. Your new balance is " + account.getBalance() + "\n"); } else { System.out.println("Not sufficient balance\n"); } return moneyWithdrawn; }
@Test public void testAddWithdraw() { // Amount before deposit and withdraw int preTransferAmountTestaccount = testAccount.getBalance().getAmount(); // Try to deposit 200 and check if desired value testAccount.deposit(new Money(200, SEK)); assertEquals( preTransferAmountTestaccount + 200, testAccount.getBalance().getAmount().intValue()); // Try to withdraw 200 and check value testAccount.withdraw(new Money(200, SEK)); assertEquals(preTransferAmountTestaccount, testAccount.getBalance().getAmount().intValue()); }
public static void main(String[] args) { Account momsSavings = new Account(1000); momsSavings.addInterest(10); System.out.println("The balance in momsSavings is $" + momsSavings.getBalance()); }
@Given("^I have deposited \\$(\\d+) in my account$") public void iHaveDeposited$InMyAccount(int amount) throws Throwable { Account myAccount = new Account(); myAccount.deposit(amount); Assert.assertEquals("Incorrect account balance -", amount, myAccount.getBalance()); }
/** * Withdraw money from a given account * * @param accNum The account number * @param custNum The customer number * @param amount The amount to withdraw * @param date The current date */ public void makeWithdraw(int accNum, int custNum, Double amount, Date date) { Account t = getAccount(accNum, custNum); Customer c = getCustomer(custNum); boolean success = t.withdraw(amount); if (!success) if (t instanceof CheckingAccount) t.setBalance(t.getBalance() - c.getOverdraftPenalty()); else System.out.println("Withdraw amount exceeds current funds."); }
public void run() { for (int x = 0; x < 5; x++) { makeWithdrawal(10); if (acct.getBalance() < 0) { System.out.println("account is overdrawn!"); } } }
// A unica alteracao do codigo private synchronized void makeWithdrawal(int amt) { if (acct.getBalance() >= amt) { System.out.println(Thread.currentThread().getName() + " is going to withdraw"); try { Thread.sleep(500); } catch (InterruptedException ex) { } acct.withdraw(amt); System.out.println(Thread.currentThread().getName() + " completes the withdrawal"); } else { System.out.println( "Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + acct.getBalance()); } }
public static void printAccounts() { System.out.println("\n---------------ACCOUNTS------------"); System.out.format("%15s%15s%15s\n", "Name", "Account #", "Balance"); System.out.format("%15s%15s%15s\n", "----", "--------", "-------"); for (Account elem : list) { System.out.format("%15s%15s%15s\n", elem.getName(), elem.getAcc_number(), elem.getBalance()); } }
public int getBalenceInfo(int pin) { if (pin == conta.getPin()) { return conta.getBalance(); } else { System.out.println("Wrong Pin"); return 0; } }
@Test public void testTransferOk() { Account senderAccount = new Account("1", 200); Account beneficiaryAccount = new Account("2", 100); mockAccountManager.updateAccount(senderAccount); mockAccountManager.updateAccount(beneficiaryAccount); expect(mockAccountManager.findAccountForUser("1")).andReturn(senderAccount); expect(mockAccountManager.findAccountForUser("2")).andReturn(beneficiaryAccount); replay(mockAccountManager); AccountService accountService = new AccountService(); accountService.setAccountManager(mockAccountManager); accountService.transfer("1", "2", 50); assertEquals(150, senderAccount.getBalance()); assertEquals(150, beneficiaryAccount.getBalance()); }
/* * Adds earned interest to the account * * @param t A reference to some arbitrary Transaction object * @param account A reference to an Account object to which the earned interest is added * @param transactionType The type of transaction (eg deposit, withdrawal) * @param amount The amount processed during the transaction * @param date The date of the transaction in the form mmddyyyy * @param fees A description of any unusual fees */ public void makeInterestDeposit( Transaction t, Account account, String transactionType, double amount, String date, String fees) { double earnedInterest = account.getBalance() * account.getCustomer().getSavingsInterest() / 100; account.addInterest(); makeTransaction(t, account, transactionType, earnedInterest, date, fees); }
public static void main(String args[]) { ExecutorService executor = Executors.newCachedThreadPool(); for (int i = 0; i < 100; i++) { executor.execute(new AddPennyTask()); } executor.shutdown(); while (!executor.isTerminated()) {} System.out.println("What it balance? " + account.getBalance()); }
// method to input accounts private static HashMap<String, Account> inputAccounts(HashMap<String, Account> acctMap) { Scanner sc = new Scanner(System.in); String accountNumber = ""; Account account; System.out.print("Please enter account number (enter -1 to stop entering account)"); accountNumber = sc.next(); sc.nextLine(); while (!accountNumber.equals("-1")) { // if account has been existed, get the current balance from hashmap if (acctMap.containsKey(accountNumber)) { // show it to console account = acctMap.get(accountNumber); System.out.println("Account existed, balance = " + account.getBalance()); } // if account has not created, add to hashmap else { account = new Account(); // set account number account.setAcctNumber(accountNumber); // prompt for name System.out.print("Enter the name for acct # " + accountNumber + ": "); account.setName(sc.nextLine()); // promp user for initial balance boolean isValidAmount = false; String amountStr = ""; while (!isValidAmount) { System.out.print("Please enter balance amount: "); amountStr = sc.next(); isValidAmount = Validator.validateDoubleWithRange(amountStr, 0, 1000000000); if (!isValidAmount) { System.out.println("Invalid amount, please try again!"); } } account.setBalance(Double.parseDouble(amountStr)); acctMap.put(account.getAcctNumber(), account); } System.out.print("Please enter account number (enter -1 to stop entering account): "); accountNumber = sc.next(); sc.nextLine(); } return acctMap; }
public static void main(String[] args) { Scanner scan = new Scanner(System.in); Account testAccount = new Account(12345, 0.00, "John Snow", "*****@*****.**", 123 - 456 - 7789); System.out.println("Thanks " + testAccount.getCustomerName() + " for banking with us." + ""); System.out.println( "Account " + testAccount.getNumber() + " current balance is $" + testAccount.getBalance()); System.out.println( "Now let's deposit a little money into that account. How much would you like to deposit?"); double addFundsEntered = scan.nextDouble(); testAccount.addFunds(addFundsEntered); System.out.println( "Now let's withdraw some of the money. How much would you like to withdraw?"); double removeFundsEntered = scan.nextDouble(); testAccount.withdrawFunds(removeFundsEntered); System.out.println("Testing VIP Constructors"); VipCustomer testVipCustomer = new VipCustomer(); System.out.println("Default VipCustomer"); System.out.println( "Thanks for banking with us " + testVipCustomer.getName() + " your credit limit is " + testVipCustomer.getCreditLimit() + "and your email on file is " + testVipCustomer.getEmailAddress()); VipCustomer testVipCustmer2 = new VipCustomer("John Smith", 10000.00); System.out.println("VipCustomer with 2 parameters"); System.out.println( "Thanks for banking with us " + testVipCustmer2.getName() + " your credit limit is " + testVipCustmer2.getCreditLimit() + "and your email on file is " + testVipCustmer2.getEmailAddress()); VipCustomer testVipCustmer3 = new VipCustomer("John Snow", 20000.00, "*****@*****.**"); System.out.println("VipCustomer with 3 parameters"); System.out.println( "Thanks for banking with us " + testVipCustmer3.getName() + " your credit limit is " + testVipCustmer3.getCreditLimit() + "and your email on file is " + testVipCustmer3.getEmailAddress()); }
public int getMoneyFromAccout(int pin, int value) { if (pin == conta.getPin()) { conta.setBalance(conta.getBalance() - value); totalMoney -= value; System.out.println("Operation completed"); return value; } else { System.out.println("Wrong Pin"); return 0; } }
public static void main(String[] args) { // init object Account account1 = new Account(50.00); Account account2 = new Account(-7.53); // print objects balance System.out.printf("account1 balance: $%.2f\n", account1.getBalance()); System.out.printf("account2 balance: $%.2f\n", account2.getBalance()); // create scanner to read user input Scanner input = new Scanner(System.in); double depositAmount; // deposite amount read from user System.out.print("Enter deposit amount for account 1: "); depositAmount = input.nextDouble(); System.out.printf("\nadding %.2f to account1 balance\n\n", depositAmount); account1.credit(depositAmount); // display message System.out.printf("account1 balance $%.2f\n", account1.getBalance()); System.out.printf("account2 balance $%.2f\n", account2.getBalance()); // prompt System.out.print("Enter deposit amount for account2: "); depositAmount = input.nextDouble(); System.out.printf("\nadding %.2f to account2 balance\n\n", depositAmount); account2.credit(depositAmount); // display balance System.out.printf("account1 balance $%.2f\n", account1.getBalance()); System.out.printf("account2 balance $%.2f\n", account2.getBalance()); }
@Test public void testTimedPayment() throws AccountDoesNotExistException { // The amounts before any ticks and payments int preTransferAmountHans = testAccount.getBalance().getAmount(); int preTransferAmountAlice = SweBank.getBalance("Alice"); // Set up the payment and tick once testAccount.addTimedPayment("Test", 1, 1, new Money(100, SEK), SweBank, "Alice"); testAccount.tick(); // There should be the same amount on each account assertEquals(preTransferAmountHans, testAccount.getBalance().getAmount().intValue()); assertEquals(preTransferAmountAlice, SweBank.getBalance("Alice").intValue()); testAccount.tick(); // 100 withdrawn from testAccount. Alice gets deposit of 100 assertEquals(preTransferAmountHans - 100, testAccount.getBalance().getAmount().intValue()); assertEquals(preTransferAmountAlice + 100, SweBank.getBalance("Alice").intValue()); // Tick for another payment testAccount.tick(); testAccount.tick(); // Another 100 withdrawn/deposit assertEquals(preTransferAmountHans - 200, testAccount.getBalance().getAmount().intValue()); assertEquals(preTransferAmountAlice + 200, SweBank.getBalance("Alice").intValue()); // Remove payment testAccount.removeTimedPayment("Test"); // Tick some times, and afterwards check if the amounts are still the same testAccount.tick(); testAccount.tick(); testAccount.tick(); testAccount.tick(); assertEquals(preTransferAmountHans - 200, testAccount.getBalance().getAmount().intValue()); assertEquals(preTransferAmountAlice + 200, SweBank.getBalance("Alice").intValue()); }
Object processInformation(Information info) { // ------------------------------------------- Account acc = (Account) accounts.get(info.getAccountId()); if (acc == null) return newProblem(ACCOUNT_NOT_FOUND); java.util.Date date = new java.util.Date(); Operation op = new Operation(); // <-- Apply admin charge op.setType(ADMIN); op.setAmount(info.getType() == BALANCE ? BAL_CHARGE : OPER_CHARGE); acc.setBalance(acc.getBalance() - op.getAmount()); op.setBalance(acc.getBalance()); op.setAccountId(acc.getId()); op.setDate(date); List l = (List) operations.get(acc.getId()); l.add(op); operations.put(acc.getId(), l); if (info.getType() == BALANCE) return acc; if (info.getType() == OPERATIONS) return l; return null; }
public double depositTwiceWithRollback(long id, double a1, double a2) { Account a; beginTx(); try { a = em.find(Account.class, id); // unsafe (nolock) a.setBalance(a.getBalance() + a1); em.flush(); commitTx(); } finally { rollbackTxIfNeeded(); } beginTx(); try { // unsafe a.setBalance(a.getBalance() + a2); em.flush(); } finally { rollbackTx(); } return a.getBalance(); }
// Third version with Exemptable interface public boolean isBalanceSufficient(Account account, double amount, Exemptable ex) { logAccess(account); boolean isBalanceSufficient = account.getBalance() - amount > 0; if (!isBalanceSufficient) { // Now, we can let the caller vary the condition if (ex.isExempt(account)) { isBalanceSufficient = true; alertOverdraw(account); } } return isBalanceSufficient; }
// First version public boolean isBalanceSufficient(Account account, double amount) { logAccess(account); boolean isBalanceSufficient = account.getBalance() - amount > 0; if (!isBalanceSufficient) { // It would be nice to let the caller vary this condition if (account.getCreditRating() > 700) { isBalanceSufficient = true; alertOverdraw(account); } } return isBalanceSufficient; }
Object processOperation(MakeOperation mo) { // ------------------------------------------- Account acc = (Account) accounts.get(mo.getAccountId()); if (acc == null) return newProblem(ACCOUNT_NOT_FOUND); if (mo.getAmount() <= 0) return newProblem(ILLEGAL_OPERATION); if (mo.getType() != DEPOSIT && mo.getType() != WITHDRAWAL) return null; if (mo.getType() == DEPOSIT) acc.setBalance(acc.getBalance() + mo.getAmount()); else if (mo.getType() == WITHDRAWAL) { if (mo.getAmount() > acc.getBalance()) return newProblem(NOT_ENOUGH_MONEY); acc.setBalance(acc.getBalance() - mo.getAmount()); } Operation op = new Operation(); op.setType(mo.getType()); op.setAmount(mo.getAmount()); op.setAccountId(acc.getId()); op.setDate(new java.util.Date()); List l = (List) operations.get(acc.getId()); l.add(op); operations.put(acc.getId(), l); return acc; }
private void spend() { String amountStr = JOptionPane.showInputDialog( this, "Input an amount to spend:", "Spend", JOptionPane.QUESTION_MESSAGE); if (amountStr == null) { return; } String accountNumberStr = JOptionPane.showInputDialog( this, "To what account number? (blank is allowed)", "Spend", JOptionPane.QUESTION_MESSAGE); if (accountNumberStr == null) { return; } try { BigDecimal amount = FORMATTER.stringToValue(amountStr); Account target; if (accountNumberStr.isEmpty()) { target = null; } else { int accountNumber = new IntegerFormatter().stringToValue(accountNumberStr); target = null; for (User user : Bank.getInstance().getUsers()) { for (Account account : user.getAccounts()) { if (account.getAccountNumber() == accountNumber) { target = account; } } } } if (target != null && (target.getType().isLoan() && target.getBalance().negate().compareTo(amount) < 0)) { throw new InvalidInputException( accountNumberStr, "account does not exist or cannot accept this deposit"); } account.withdraw(amount); if (target != null) { target.deposit(amount); } controller.updateBankDisplay(); } catch (ParseException px) { controller.handleException(this, px); } catch (InvalidInputException iix) { controller.handleException(this, iix); } catch (InsufficientFundsException ifx) { controller.handleException(this, ifx); } }
public static void main(String[] args) { Account account = new Account(); MyThread thread1 = new MyThread(100, 10, account); MyThread thread2 = new MyThread(-100, 10, account); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (Exception e) { e.printStackTrace(); } System.out.println(account.getBalance()); }
private void transfer() { String amountStr = JOptionPane.showInputDialog( this, "Input an amount to transfer:", "Transfer", JOptionPane.QUESTION_MESSAGE); if (amountStr == null) { return; } try { BigDecimal amount = FORMATTER.stringToValue(amountStr); Set<Account> accounts = new HashSet<Account>(controller.getCurrentUser().getAccounts()); Iterator<Account> iterator = accounts.iterator(); while (iterator.hasNext()) { Account account = iterator.next(); if (account.getType().isLoan() && account.getBalance().negate().compareTo(amount) < 0) { iterator.remove(); } } if (!accounts.isEmpty()) { Account account = (Account) JOptionPane.showInputDialog( this, "Choose an account:", "Transfer", JOptionPane.QUESTION_MESSAGE, null, accounts.toArray(), accounts.iterator().next()); if (account != null) { this.account.withdraw(amount); account.deposit(amount); controller.updateBankDisplay(); } } else { JOptionPane.showMessageDialog( this, "No accounts can accept that balance.", "Transfer failed", JOptionPane.ERROR_MESSAGE); return; } } catch (ParseException px) { controller.handleException(this, px); } catch (InvalidInputException iix) { controller.handleException(this, iix); } catch (InsufficientFundsException ifx) { controller.handleException(this, ifx); } }