private void transfer(final Date date, final Account account1, final Account account2) { persistence.runInTransaction( em -> { BigDecimal amount1 = randomExpenseAmount(account1, date, 0.5); if (BigDecimal.ZERO.compareTo(amount1) >= 0) return; BigDecimal amount2 = transferAmount(account1, account2, amount1); Operation operation = metadata.create(Operation.class); operation.setOpType(OperationType.TRANSFER); operation.setOpDate(date); operation.setAcc1(account1); operation.setAmount1(amount1); operation.setAcc2(account2); operation.setAmount2(amount2); em.persist(operation); log.info( "Transfer: " + date + ", " + account1.getName() + ", " + amount1 + ", " + account2.getName() + ", " + amount2); }); }
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 void fix(Account from, Account to, int money) throws InterruptedException { if (from.hashCode() > to.hashCode()) { synchronized (from) { Thread.sleep(2 * 1000L); System.out.println("get from" + from.getName() + ",waiting " + to.getName()); synchronized (to) { decreaseAccount(from, to, money); } } } else if (to.hashCode() > from.hashCode()) { synchronized (to) { Thread.sleep(2 * 1000L); System.out.println("get from" + from.getName() + ",waiting " + to.getName()); synchronized (from) { decreaseAccount(from, to, money); } } } else { synchronized (xLock) { synchronized (to) { synchronized (from) { decreaseAccount(from, to, money); } } } } }
public void transforMoney(Account from, Account to, int money) throws InterruptedException { synchronized (from) { Thread.sleep(2 * 1000L); System.out.println("get from" + from.getName() + ",waiting " + to.getName()); synchronized (to) { decreaseAccount(from, to, money); } } }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Account)) return false; Account other = (Account) obj; if (name == null) { if (other.getName() != null) return false; } else if (!name.equals(other.getName())) return false; return true; }
/** * Deliveres notification to the user that an email has been dropped. Typically due to size * restriction * * @param account * @param messageNumber * @param message * @throws Exception */ public void saveMessageDroppedNotification( Account account, int messageNumber, Message message, int reportedSize) throws Exception { MessageParser parser = new MessageParser(); Email email = new Email(); email.setSubject( "Your email"); // ReceiverUtilsTools.subSubject(parser.parseMsgSubject(message), // subjectSize)); email.setFrom(parser.parseMsgAddress(message, "FROM", false)); email.setTo(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "TO", true))); email.setCc(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "CC", true))); email.setBcc(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "BCC", true))); email.setMaildate(ReceiverUtilsTools.dateToStr(message.getSentDate())); email.setStatus("0"); email.setUserId(account.getUser_id()); email.setMessage_type("EMAIL"); Body body = new Body(); String droppedMessage = getEmailDroppedMessage(account, getMessageDate(message), reportedSize, email.getFrom()); body.setData(droppedMessage.getBytes()); email.setBodySize(droppedMessage.length()); int saveStatus = DALDominator.newSaveMail(account, email, body); if (log.isDebugEnabled()) log.debug( String.format( "[%s] msgNum=%d, saving completed for dropped message with status %s", account.getName(), messageNumber, saveStatus)); }
public ServerSolution() { accountMap = new HashMap<String, Account>(); File file = new File(fileName); ObjectInputStream in = null; try { if (file.exists()) { System.out.println("Reading from file " + fileName + "..."); in = new ObjectInputStream(new FileInputStream(file)); Integer sizeI = (Integer) in.readObject(); int size = sizeI.intValue(); for (int i = 0; i < size; i++) { Account acc = (Account) in.readObject(); if (acc != null) accountMap.put(acc.getName(), acc); } } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { t.printStackTrace(); } } } }
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 void updateProfile(String key, Account pAccount) throws SQLException, ConnectionException, MissingDataException, NullAccountException, ProfileException, PasswordException, EmailException { try (Connection connect = DBConnection.getConnection()) { pAccount = testAccount(pAccount); String sql = "UPDATE account" + "set name = '" + Utility.Replace(testProfileData(pAccount.getName())) + "', surname = '" + Utility.Replace(testProfileData(pAccount.getSurname())) + "', password = '******', secondaryEmail = '" + testEmail(pAccount.getSecondaryEmail()) + "WHERE email = '" + key + "'"; String sql2 = "UPDATE " + pAccount.getTypeAccount(); if (pAccount instanceof PhdStudent) { sql2 += " set telephone = '" + testProfileData(((PhdStudent) pAccount).getTelephone()) + "', link = '" + testProfileData(((PhdStudent) pAccount).getLink()) + "', deparment = '" + testProfileData(((PhdStudent) pAccount).getDepartment()) + "', researchInterest = '" + testProfileData(((PhdStudent) pAccount).getResearchInterest()) + "' WHERE fkAccount = '" + testProfileData(((PhdStudent) pAccount).getSecondaryEmail()); } if (pAccount instanceof Professor) { sql2 += " set link = '" + ((Professor) pAccount).getLink() + "', set department = '" + ((Professor) pAccount).getDepartment() + "' WHERE fkAccount = '" + ((Professor) pAccount).getSecondaryEmail() + "'"; } if (pAccount.getTypeAccount().equals("basic")) // aggiorna solo info base Utility.executeOperation(connect, sql); else { Utility.executeOperation(connect, sql); Utility.executeOperation(connect, sql2); } connect.commit(); } }
/** * It so happens Gmail sends us sent messages as well as received once * * @param account * @param message * @return * @throws Exception */ protected boolean isSentMessage(Account account, Message message) throws Exception { MessageParser parser = new MessageParser(); if (EmailUtil.isFromSameAsAccount(account, message)) { String to = parser.parseMsgAddress(message, "TO", true); String cc = parser.parseMsgAddress(message, "CC", true); if (!to.contains(account.getName()) && !cc.contains(account.getName())) { log.warn( String.format( "msgNum=%d, message is 'sent' not 'received' discarding, for %s", message.getMessageNumber(), account.getName())); return true; } } return false; }
public static int get_account_savings(String name) { int acc_num = 0; ResultSet result = null; for (Account elem : list) { if (elem.getName().equalsIgnoreCase(name) && elem.getAcc_type().equalsIgnoreCase("Saving")) return elem.getAcc_number(); } return 0; }
public void printHighestBalance() { // prints the accounts from highest amount to lowest, with those who have empty accounts last ajf.dispose(); ajf = new AdminRunningFrame(this); StringBuilder stringResults = new StringBuilder(); String header = header(); stringResults.append(header); if (!cust.isEmpty()) { ArrayList<Account> allAccounts = new ArrayList<Account>(); ArrayList<Customer> CustomersNoAccounts = new ArrayList<Customer>(); for (Customer c : cust) { ArrayList<Account> accounts = c.getAccounts(); if (!accounts.isEmpty()) { // Concatenates all the accounts together for easy sorting allAccounts.addAll(accounts); } // Adds customers without accounts to a separate list to be printed at the end of all the // others else { CustomersNoAccounts.add(c); } } if (!allAccounts.isEmpty()) { Collections.sort(allAccounts, Account.CompareBalances); for (Account a : allAccounts) { if (a.checkActive()) { String id = a.getID(); String name = a.getName().toUpperCase(); String pin = a.getPin(); String accountNumber = a.returnNumber(); double balance = a.returnBalance(); String balanceAsString = formatter.format(balance); String customerInfo = printAdminInfo(name, id, accountNumber, pin, balanceAsString); stringResults.append(customerInfo); } } } if (!CustomersNoAccounts.isEmpty()) { Collections.sort(CustomersNoAccounts, Customer.CompareName); for (Customer c : CustomersNoAccounts) { String id = c.returnID(); String name = c.getName().toUpperCase(); String pin = c.returnPin(); String noAccounts = String.format("%-20s %-9s %-10s\n", name, id, pin); stringResults.append(noAccounts); } } String resultsAsString = stringResults.toString(); ajf.printInfo(resultsAsString); } }
private void income( final Date date, final Account account, final Category category, final BigDecimal amount) { persistence.runInTransaction( em -> { Operation operation = metadata.create(Operation.class); operation.setOpType(OperationType.INCOME); operation.setOpDate(date); operation.setAcc2(account); operation.setCategory(category); operation.setAmount2(amount); em.persist(operation); log.info("Income: " + date + ", " + account.getName() + ", " + amount); }); }
boolean isMessageTooBig(Folder folder, Account account, Message message, int messageNumber) throws Exception { int messageSize = (folder instanceof POP3Folder) ? ((POP3Folder) folder).getMessageSize(messageNumber) : getMessageSize(message, account); boolean messageTooBig = messageSize > maximumMessageSize; if (messageTooBig) { log.warn( String.format( "msgNum=%d, message is too big %d bytes, discarding for %s", messageNumber, messageSize, account.getName())); saveMessageDroppedNotification(account, messageNumber, message, messageSize); } return messageTooBig; }
@Test public void getAccountTest() throws IOException, VscaleException { Result<Account> query = this.api.account(); Account account = query.get(); assertNotNull(account.getActivationDate()); assertNotNull(account.getCountry()); assertNotNull(account.getId()); assertNotNull(account.getEmail()); assertNotNull(account.getFaceId()); assertNotNull(account.getState()); assertNotNull(account.getLocale()); assertNotNull(account.getMobile()); assertNotNull(account.getName()); assertNotNull(account.getSurname()); }
public static int find_Account_by_name(String name) { int check = 0; int sav = 0; int ret = 3; for (Account elem : TransactionApp.list) { if (elem.getName().equalsIgnoreCase(name)) { if (elem.getAcc_type().equalsIgnoreCase("Checking")) check = 1; if (elem.getAcc_type().equalsIgnoreCase("Saving")) sav = 1; } } if (check == 1 && sav == 1) ret = 0; else if (check == 1 && sav != 1) ret = 1; else if (sav == 1 && check != 1) ret = 2; else ret = 3; return ret; }
public void fixByTryLock(Account from, Account to, int money) throws InterruptedException { while (true) { if (from.lock.tryLock()) { System.out.println("account" + from.getName() + " sleeping"); try { if (to.lock.tryLock()) { try { decreaseAccount(from, to, money); // success , return return; } finally { to.lock.unlock(); } } } finally { from.lock.unlock(); } } } }
@Test public void testPostAccountSuccess() throws Exception { Account a = accountManager.findAccount("123456001"); a.setEmail("*****@*****.**"); // Update the email mockMvc .perform( post("/accounts/{acctId}", "123456001") .param("name", a.getName()) // Providing all the params that would have been sent in // the form .param("dateOfBirth", formatDate(a.getDateOfBirth())) .param("email", a.getEmail()) .param("receiveNewsletter", (a.isReceiveNewsletter() ? "1" : "0")) .param("receiveMonthlyEmailUpdate", (a.isReceiveMonthlyEmailUpdate() ? "1" : "0"))) .andExpect(status().isFound()) // Because this is a redirect .andExpect(redirectedUrl("123456001")); // The redirect URL // provided by the // controller }
private boolean newAccountFactory(String type, String name, float balance) throws IllegalArgumentException { Account acc; if ("Checking".equals(type)) { acc = new Checking(name, balance); } else if ("Savings".equals(type)) { acc = new Savings(name, balance); } else { throw new IllegalArgumentException("Bad account type:" + type); } try { accountMap.put(acc.getName(), acc); } catch (Exception exc) { return false; } return true; }
public void action() { try { ContentElement content = getContentManager().extractContent(request); CreateAccount ca = (CreateAccount) ((Action) content).getAction(); Account acc = new Account(); String id = generateId(); acc.setId(id); acc.setName(ca.getName()); Result result = new Result((Action) content, acc); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); getContentManager().fillContent(reply, result); send(reply); accounts.put(id, acc); operations.put(id, new ArrayList()); System.out.println("Account [" + acc.getName() + " # " + acc.getId() + "] created!"); } catch (Exception ex) { ex.printStackTrace(); } }
@Test public void testPostAccountFailValidation() throws Exception { Account a = accountManager.findAccount("123456001"); a.setEmail("bogusemail"); // Update the email with bad email address mockMvc .perform( post("/accounts/{acctId}", "123456001") .param("name", a.getName()) // Providing all the params that would have been sent in // the form .param("dateOfBirth", formatDate(a.getDateOfBirth())) .param("email", a.getEmail()) .param("receiveNewsletter", (a.isReceiveNewsletter() ? "1" : "0")) .param("receiveMonthlyEmailUpdate", (a.isReceiveMonthlyEmailUpdate() ? "1" : "0"))) .andExpect(model().attributeHasErrors("account")) .andExpect(model().attributeErrorCount("account", 1)) .andExpect(model().attributeHasFieldErrors("account", "email")) .andExpect(status().isOk()) // Because this is a forward to the // same view .andExpect(view().name("accounts/edit")); }
@Test public void someImmutability() { AccountBalance b1 = new AccountBalance(42.4); assertEquals(42.4, b1.getBalance()); b1 = b1.add(2); assertEquals(44.4, b1.getBalance()); Account account = new Account("Stevens Account", new ArrayList<>()); assertEquals(0, account.getTransactions().size()); account = account.addTransaction(b1); assertEquals(1, account.getTransactions().size()); assertEquals(b1, account.getTransactions().head()); // interesting: Normally, there would be a method setName(). We don't want setters here, so name // it "rename" :) account = account.rename("Former Stevens Account"); assertEquals("Former Stevens Account", account.getName()); assertEquals(1, account.getTransactions().size()); assertEquals(b1, account.getTransactions().head()); }
public void testFindByCreditCard() { Account account = repository.findByCreditCard("1234123412341234"); // assert the returned account contains what you expect given the state of the database // and the Account Hibernate mapping configuration assertNotNull("account should never be null", account); assertEquals("wrong entity id", Long.valueOf(0), account.getEntityId()); assertEquals("wrong account number", "123456789", account.getNumber()); assertEquals("wrong name", "Keith and Keri Donald", account.getName()); assertEquals("wrong beneficiary collection size", 2, account.getBeneficiaries().size()); Beneficiary b1 = account.getBeneficiary("Annabelle"); assertNotNull("Annabelle should be a beneficiary", b1); assertEquals("wrong savings", MonetaryAmount.valueOf("0.00"), b1.getSavings()); assertEquals( "wrong allocation percentage", Percentage.valueOf("50%"), b1.getAllocationPercentage()); Beneficiary b2 = account.getBeneficiary("Corgan"); assertNotNull("Corgan should be a beneficiary", b2); assertEquals("wrong savings", MonetaryAmount.valueOf("0.00"), b2.getSavings()); assertEquals( "wrong allocation percentage", Percentage.valueOf("50%"), b2.getAllocationPercentage()); }
private void expense(final Date date, final Account account, final Context context) { persistence.runInTransaction( em -> { int categoryIdx = (int) Math.round(Math.random() * (context.expenseCategories.size() - 1)); Category category = context.expenseCategories.get(categoryIdx); if (category == null) return; int categoryWeight = context.expenseCategories.size() - categoryIdx; BigDecimal amount = randomExpenseAmount(account, date, 0.1 + (categoryWeight * 0.05)); if (BigDecimal.ZERO.compareTo(amount) >= 0) return; Operation operation = metadata.create(Operation.class); operation.setOpType(OperationType.EXPENSE); operation.setOpDate(date); operation.setAcc1(account); operation.setCategory(category); operation.setAmount1(amount); em.persist(operation); log.info("Expense: " + date + ", " + account.getName() + ", " + amount); }); }
public static void addAccounts() { try { for (Account elem : new_list) { String new_accounts = "insert into BANK_ACCT (ACC_NUMBER, ACC_TYPE, NAME, BALANCE)values(" + elem.getAcc_number() + " ,'" + elem.getAcc_type() + "' ,'" + elem.getName() + "'," + elem.getBalance() + ")"; // System.out.println(new_accounts); PreparedStatement preStatement = conn.prepareStatement(new_accounts); preStatement.executeQuery(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
/** * @param currentAccount existing account data * @return merged account data */ @Override public Account mergeWithDelegate(final Account currentAccount) { final DefaultMutableAccountData accountData = new DefaultMutableAccountData(this); if (externalKey != null && currentAccount.getExternalKey() != null && !currentAccount.getExternalKey().equals(externalKey)) { throw new IllegalArgumentException( String.format( "Killbill doesn't support updating the account external key yet: new=%s, current=%s", externalKey, currentAccount.getExternalKey())); } else { // Default to current value accountData.setExternalKey(currentAccount.getExternalKey()); } if (currency != null && currentAccount.getCurrency() != null && !currentAccount.getCurrency().equals(currency)) { throw new IllegalArgumentException( String.format( "Killbill doesn't support updating the account currency yet: new=%s, current=%s", currency, currentAccount.getCurrency())); } else { // Default to current value accountData.setCurrency(currentAccount.getCurrency()); } if (billCycleDayLocal != null && billCycleDayLocal != 0 && currentAccount.getBillCycleDayLocal() != 0 && !billCycleDayLocal.equals(currentAccount.getBillCycleDayLocal())) { throw new IllegalArgumentException( String.format( "Killbill doesn't support updating the account BCD yet: new=%s, current=%s", billCycleDayLocal, currentAccount.getBillCycleDayLocal())); } else if (billCycleDayLocal != null && billCycleDayLocal != 0) { // Junction sets it accountData.setBillCycleDayLocal(billCycleDayLocal); } else { // Default to current value accountData.setBillCycleDayLocal(currentAccount.getBillCycleDayLocal()); } // Set all updatable fields with the new values if non null, otherwise defaults to the current // values accountData.setEmail(Objects.firstNonNull(email, currentAccount.getEmail())); accountData.setName(Objects.firstNonNull(name, currentAccount.getName())); accountData.setFirstNameLength( Objects.firstNonNull(firstNameLength, currentAccount.getFirstNameLength())); accountData.setPaymentMethodId( Optional.<UUID>fromNullable(paymentMethodId) .or(Optional.<UUID>fromNullable(currentAccount.getPaymentMethodId())) .orNull()); accountData.setTimeZone(Objects.firstNonNull(timeZone, currentAccount.getTimeZone())); accountData.setLocale(Objects.firstNonNull(locale, currentAccount.getLocale())); accountData.setAddress1(Objects.firstNonNull(address1, currentAccount.getAddress1())); accountData.setAddress2(Objects.firstNonNull(address2, currentAccount.getAddress2())); accountData.setCompanyName(Objects.firstNonNull(companyName, currentAccount.getCompanyName())); accountData.setCity(Objects.firstNonNull(city, currentAccount.getCity())); accountData.setStateOrProvince( Objects.firstNonNull(stateOrProvince, currentAccount.getStateOrProvince())); accountData.setCountry(Objects.firstNonNull(country, currentAccount.getCountry())); accountData.setPostalCode(Objects.firstNonNull(postalCode, currentAccount.getPostalCode())); accountData.setPhone(Objects.firstNonNull(phone, currentAccount.getPhone())); accountData.setIsMigrated(Objects.firstNonNull(isMigrated, currentAccount.isMigrated())); accountData.setIsNotifiedForInvoices( Objects.firstNonNull(isNotifiedForInvoices, currentAccount.isNotifiedForInvoices())); return new DefaultAccount(currentAccount.getId(), accountData); }
// Test the getName function @Test public void nametest() { Account a = new Account(); a.setName("Alice"); assertEquals(a.getName(), "Alice"); }
@SuppressWarnings("unchecked") public static void main(String[] args) { int tr_id = 0; transaction = new ArrayList<Transaction>(); list = new ArrayList<Account>(); new_list = new ArrayList<Account>(); // list for new accounts del_list = new ArrayList<Account>(); // accounts to remove Scanner sc = new Scanner(System.in); Account ac = null; try { connectSQL(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Read accounts to arrayList getAccounts(); // print accounts System.out.printf("%20s%15s%15s%15s\n", "Name", "Account #", "Balance", "Account Type"); for (Account elem : list) { System.out.printf( "%20s%15s%15s%15s\n", elem.getName(), elem.getAcc_number(), elem.getBalance(), elem.getAcc_type()); } // Loops to add/remove accounts while (true) { boolean flag = false; System.out.println("Enter account number or -1 to stop entering accounts: "); String account_num = sc.nextLine(); whilelabel: while (!Validation.validate_Account_Num(account_num)) { System.out.println("Invalid! Enter an account number or -1 to stop entering accounts: "); account_num = sc.nextLine(); } if (Integer.parseInt(account_num) < 0) // EXIT break; else { for (Account elem : list) { if (Integer.parseInt(account_num) == elem.getAcc_number()) { flag = true; System.out.println("Account present, balance is: " + elem.getBalance()); System.out.println("Enter d to delete account, ENTER to continue "); String response = sc.nextLine(); if (response.equalsIgnoreCase("d")) { if (elem.getBalance() != 0) { System.out.println("Cannot close account: Non Zero Balance"); flag = true; break; } list.remove(elem); del_list.add(elem); System.out.println("Account removed"); System.out.println("Current Accounts:"); for (Account elem2 : list) { System.out.printf( "%15s%15d%15f%15s\n", elem2.getName(), elem2.getAcc_number(), elem2.getBalance(), elem2.getAcc_type()); } } flag = true; break; } } if (flag) continue; // continue with while ac = new Account(); ac.setAcc_number(Integer.parseInt(account_num)); System.out.println("Enter the name for your account# " + account_num); String name = sc.nextLine(); int type = find_Account_by_name(name); System.out.println(type); // if name exists check acc_type // if both exists prompt again if (type != 3) { if (type == 1) { System.out.println("Would you like to open a savings account: y/n"); String response = sc.nextLine(); if (!response.equalsIgnoreCase("y")) continue; else { ac.setAcc_type("Saving"); ac.setAcc_number(generate_Unique_acc_num()); } } else if (type == 2) { System.out.println("Would you like to open a Checking account: y/n"); String response = sc.nextLine(); if (!response.equalsIgnoreCase("y")) continue; else ac.setAcc_type("Checking"); ac.setAcc_number(generate_Unique_acc_num()); } else if (type == 0) { System.out.println("You have both accounts! "); break; } } else // no accounts for this name { System.out.println("Enter c for Checking: s for Savings"); String acc_type = sc.nextLine(); if (acc_type.equalsIgnoreCase("C")) ac.setAcc_type("Checking"); else ac.setAcc_type("Saving"); } ac.setName(name); System.out.println("Enter the balance for account number# " + ac.getAcc_number()); ac.setBalance(Double.parseDouble(sc.nextLine())); System.out.println("balance " + ac.getBalance()); new_list.add(ac); } } // Loop to perform transactions while (true) { System.out.println( "Enter a transaction type: (c:Check, dc:Debit Card, d:Deposit, tr:transfer, or w:Withdrawl) or -1 to finish"); String tr = sc.nextLine(); if ((!tr.equalsIgnoreCase("-1")) && (!tr.equalsIgnoreCase("w")) && (!tr.equalsIgnoreCase("d")) && (!tr.equalsIgnoreCase("c")) && (!tr.equalsIgnoreCase("dc")) && (!tr.equalsIgnoreCase("tr"))) continue; if (tr.equalsIgnoreCase("-1")) break; System.out.println("Enter your account# "); String account_num = sc.nextLine(); while (!Validation.validate_Account_Num(account_num)) { System.out.println("Invalid! Enter an account number: "); account_num = sc.nextLine(); } int acc_index = TransactionApp.find_Account(account_num); if (acc_index == -1) { System.out.println("Invalid Account #, try again"); continue; } else { System.out.println("Balance : " + list.get(acc_index).getBalance()); System.out.println("Enter Amount: "); String db = sc.nextLine(); while (!Validation.validate_Amount(db)) { System.out.println("Enter Amount: "); db = sc.nextLine(); } double am = Double.parseDouble(db); ; // sc.nextLine(); System.out.println("Enter Date MM/DD/YY"); String date = sc.nextLine(); while (!Validation.validate_Date(date)) { System.out.println("Invalid date! Enter Again: MM/DD/YY"); date = sc.nextLine(); } if (tr.equalsIgnoreCase("d")) tr_id = 1; else if (tr.equalsIgnoreCase("dc")) tr_id = 4; else if (tr.equalsIgnoreCase("c")) tr_id = 2; else if (tr.equalsIgnoreCase("w")) tr_id = 3; else if (tr.equalsIgnoreCase("tr")) tr_id = 5; if (tr.equalsIgnoreCase("c") || tr.equalsIgnoreCase("d")) // deposit { transaction.add( Transaction.getTransaction(Integer.parseInt(account_num), am, date, tr_id)); } else if (tr.equalsIgnoreCase("tr")) { System.out.println("Enter account number to Deposit To"); String to_acc_num = sc.nextLine(); Validation.validate_Account_Num(to_acc_num); int index_to_acc = find_Account(to_acc_num); // need to be checked int index_from_acc = find_Account(account_num); while (true) { if (list.get(index_from_acc).getBalance() < am) { System.out.println( "Insufficient Funds, current balance : " + list.get(index_from_acc).getBalance()); System.out.println("Enter another amount "); String new_amount = sc.nextLine(); am = Double.parseDouble(new_amount); } else break; } transaction.add( Transaction.getTransaction(Integer.parseInt(to_acc_num), am, date, tr_id)); // deposit am = 0 - am; transaction.add( Transaction.getTransaction( // withdraw Integer.parseInt(account_num), am, date, tr_id)); } else // Withdrawal { double rem_bal = 0; String ac_type = list.get(find_Account(account_num)).getAcc_type(); if (ac_type.equalsIgnoreCase("Checking")) { double c_balance = list.get(find_Account(account_num)).getBalance(); if (c_balance < am) { String cust_name = list.get(find_Account(account_num)).getName(); int type = find_Account_by_name(cust_name); if (type == 0) // has a saving account { System.out.println("Came here"); int acc_num2 = get_account_savings(cust_name); double s_balance = list.get(find_Account(Integer.toString(acc_num2))).getBalance(); if (c_balance + s_balance < am) { System.out.println("Insufficient funds"); continue; } else { rem_bal = 0 - am + c_balance - 15; double c_bal = 0 - c_balance; transaction.add( Transaction.getTransaction( Integer.parseInt(account_num), c_bal, date, tr_id)); transaction.add(Transaction.getTransaction(acc_num2, rem_bal, date, tr_id)); continue; } } else { System.out.println("Insufficient funds"); continue; } } } am = 0 - am; transaction.add( Transaction.getTransaction(Integer.parseInt(account_num), am, date, tr_id)); } } } sc.close(); Collections.sort(transaction); printTransactions(); perform_Transactions(); // printAccounts(); // write back the modified account info removeAccounts(); addAccounts(); upDateDB(); }
Employee(Account account) { super(account.getId(), account.getName()); }