Specification
A bank account is created with an initial balance read in from the user. It offers a menu so the user can deposit and withdraw money, and see the balance. It also gets daily interest. The account menu choices are
d:deposit money: read in thea mount
w:withdraw money: read in the amount, and validate it
s:see the balance
x:exit anything
else: help
A customer has three bank accounts,named credit, savings, and term; the annual interest rates are 0%, 1.2%, and 3.4%. The customer menu lets the user choose an account add interest, or see all balances. The menu choices are:
a:choose an account: enter the name
i: add interest to all accounts
s: show all accounts
x:exit
anything else: help
Add interest. Interest is added to a running total each day, and this total interest is added to the balance at the end of each month. The
bank adds the interest to an interest field everyday, and at the end of each month adds this amount to the balance and sets the interest
back to zero.
The menu choice adds daily interest to each account for 30 days, then adds the interest to the balance at the end of the month of 30 days.
The interest rate is expressed as an annual rate in percent, such as 3.4% per annum.
You have to convert it to a daily interest rate.
A normal year has 365 days. A leap year occurs every four years and has 366 days. The standard way to handle leap years is to use a year with 365.25 days.
Below is what I have so far; My question is how do I finish the string toString method() and choose method,
import java.util.*;
public class Customer
{ public static void main(String[] args)
{ new Customer(); }
public Customer()
{
setup();
}
private void setup()
{
accounts.add(new Account("",0.0));
accounts.add(new Account("",0.0));
accounts.add(new Account("",0.0));
}
public void use()
{
char choice;
while((choice = readChoice()) != 'x')
{
switch(choice)
{
case 'a': choose(); break;
case 'i': addInterest(); break;
case 's': show(); break;
default: help();
}
}
}
private char readChoice()
{ return 'x'; }
private void choose()
{
// ask for acount
// search for that ;particular accounts using account(name)
// use the newly found account (given that it is found)
}
private String readName()
{
//gives accountName you are searching for
System.out.print("??? account ???; ");
return In.nextLine();
}
private Account account(String name)
{ return null; }
private void addInterest()
{ for (Account account: accounts)
{ for (int i = 0; i < 30; i++)
account.addDailyInterest();
account.addMonthlyInterest(); }}
private void help()
{ String s = "The menu choices are";
s += "\n a: choose an account";
s += "\n i: add interest to all accounts";
s += "\n s show";
s += "\n x exit";
System.out.println(s); }
private void show()
{
System.out.println(this);
}
public String toString()
{ String s = "";
// loop through each account
// add each account toString();
// seperate each account object using a new line.
return s;
}
}
well, does it compile at all? Normally I would go with the Customer class having a private List<Account> accountList which would be easy to extended (i see the accounts.add(new Account("",0.0)); but no List declaration)
Then overwrite toSting method in Account so that it will print what suits You best. Finally in the Customer just iterate over the accountList like:
public String toString()
{ String s = "";
for (Account account:accountList){
s += account.toString() + "\n";
}
return s;
}
Related
I have created this bank account class constructor in java that makes it possible to create any number of accounts. This is part of an assignment for my java course. However, I have to manually specify each attribute of the accounts (Account ID, and balance).
What I want to do is get the user involved. For example, the user should be prompted if they want to create a new account. If they answer yes, they should be able to set the account number (weird? I know) and the account balance. The program should then create the account for them using the inputs.
I already have the options for checking account balance, making deposit or withdrawal that is working as expected, however, I want it to work for multiple accounts created. For example, the user is prompted if they want to create new account, and if yes, specify account number and balance. If they want to check the status of existing accounts, the program should give them an option of which account they want to get info about. Then the program should go through the routine behavior of displaying the prompts that I have already created.
It would also be nice if the code lets the user to create multiple accounts at once. For example:
In main, create an array of 10 Account objects with id 0 - 9 and starting balance of $100 each.
Prompt the user for an id.
Prompt the user for an amount to withdraw or deposit (or both).
Modify that Account, then print its balance.
Here is my existing class constructor portion:
// Bank account class creator
public class Account {
// Create attributes for the Account class
private int id;
private double balance;
private double withdraw;
private double deposit;
private static double annualRate;
private static String dateCreated;
// Create default constructor
Account() {
id = 0;
balance = 0;
java.util.Date date = new java.util.Date();
dateCreated = date.toString();
annualRate = 4.5;
}
// Create constructor which allows input values
Account(int accountId, double accountBalance) {
this.id = accountId;
this.balance = accountBalance;
}
// Getter for account ID
int getId() {
return this.id;
}
// Getter for account balance
double getBalance() {
return this.balance;
}
// Getter for annual interest rate
double getAnnualRate() {
return this.annualRate;
}
// Getter for date
String getDate() {
return this.dateCreated;
}
// Getter for monthly interest amount
double getMonthlyInterest() {
return this.balance * this.annualRate / 1200;
}
// Getter for annual interest amount
double getAnnualInterest() {
return this.balance * this.annualRate / 100;
}
// Validate deposit (filter negative numbers out)
double deposit(double depositAmount) {
if (depositAmount > 0) {
this.balance = this.balance + depositAmount;
return this.balance;
}
else return 0;
}
// Validate withdraw (filter negative numbers out)
double withdraw(double withdrawAmount) {
if (withdrawAmount > 0) {
this.balance = this.balance - withdrawAmount;
return this.balance;
}
else return 0;
}
// Validate ID (filter negative numbers out)
void setId(int accountId) {
if (accountId > 0)
this.id = accountId;
else
this.id = 0;
}
// Validate interest rate (filter negative numbers out)
void setAnnualRate(double currentInterest) {
if (currentInterest > 0)
this.annualRate = currentInterest;
else
this.annualRate = 0;
}
// Setter for balance
void setBalance() {
this.balance = this.balance + this.deposit - this.withdraw;
}
}
Here is the main code that uses the constructor to create accounts:
// Bank account tester
import java.util.Scanner; // import java Scanner utility
public class TestAccount {
public static void main(String[] args) {
Account account1 = new Account(); // Create a new account
Scanner input = new Scanner(System.in); // Create a Scanner object
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
System.out.println("");
System.out.print("Enter choice: ");
int userInput = input.nextInt(); // Get input from the user
while (userInput != 4) { // Start of loop to check for exit condition
if(userInput == 1) {
// Display account balance, monthly interest and current date
System.out.printf("Balance: $%.2f\n" , account1.getBalance());
System.out.printf("Monthly interest $%.2f\n" , account1.getMonthlyInterest());
System.out.println("Date created: " + account1.getDate());
}
else if (userInput == 2) {
// Deposit funds to account
System.out.println("Enter amount to deposit:");
double inputAmount = input.nextDouble();
account1.deposit(inputAmount);
}
else if (userInput == 3) {
// Withdraw funds from account
System.out.println("Enter amount to withdraw:");
double inputAmount = input.nextDouble();
account1.withdraw(inputAmount);
} else
// Prompt the user to input option choice if they input invalid option
System.out.println("That is not a valid choice. Please enter a valid choice; ");
// Continue displaying the options until the user's option is to exit
System.out.println("");
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
userInput = input.nextInt(); // Continue getting inputs until user chooses to exit
}
input.close(); // close the input method
// Display an exit message when the user chooses to exit
System.out.println("Thank you for using our banking software ");
}
}
I would also appreciate if you could point out to any error or redundancy in my code, for example incorrect use of static or redundant "this." keyword.
Few thing regarding of possible refactoring:
Invalid use of static in Account:
the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
Blockquote
annualRate and dateCreated should NOT be static as it means that these values will be shared among all instances of Account class.
Its possible to remove duplicated code for print of program options:
private void printHelp() {
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
}
I have written a code that takes input as Account details and displays the details by using ArrayList. I however want the list to fetch a particular/specific account details only for a data. Lets say i stored account number details for 127783 and 127784. Now i want only account number 127783 details. How do i fetch that using arrayList. If it doesn't happen with an ArrayList then what to use.
package com.techlabs.account;
import java.util.ArrayList;
import java.util.Scanner;
public class AccountMenu {
static int accountno;
String name;
double balance;
ArrayList a = new ArrayList();
public AccountMenu() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
if (number == 1) {
System.out.println("Enter the Account no.");
accountno = in.nextInt();
a.add(accountno);
System.out.println("Enter the name");
name = in.next();
a.add(name);
System.out.println("Enter the Balance");
balance = in.nextDouble();
a.add(balance);
}
if (number == 2) {
System.out.println("Account details are :");
for (Object b : a) {
System.out.println(b);
}
}
if (number == 3) {
System.out.println("Enter the account number");
accountno=in.nextInt();
if (a.contains(accountno)) {
System.out.println(a);
}
}
if (number == 4) {
System.out.println("Exit");
}
System.out.println("Enter the option :1. Open Account 2. Show Account details 3.Retrieve details by Searching Account Number and 4. Exit again");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu am = new AccountMenu();
}
}
Instead of dropping everything into a list of objects I would create a class for storing account details (with members of account number, name, balance).
I would store these in a Map < Integer, Account >. When you need a specific account's detail you can say map.get(accountNumber) and you will get back your specific Account instance.
Edit:
A wrapper class to hold Account details:
public Class AccountDetails{
public final int accountNumber;
public final String name;
public final int balance;
constructor
}
Instead of arraylist a should be:
Map<Integer, AccountDetails> a = new HashMap<>();
Where your create new accounts:
AccountDetails accountDetails = new AccountDetails(accountno, name, balance);
a.put(accountno, accountDetails)
Where you print details you should ask for the account number from the user, and after that:
System.out.println(a.get(accountno));
Of course to see something meaningful you should write a toString() method for the AccountDetails class.
I found a lot of errors relatying to POO in your code. Please check the code below and study OO concepts. I created a private class to represent the accounts. That way you can have an arraylist of account objects.
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication5 {
private static final class Account {
int accountno;
String name;
double balance;
#Override
public String toString() {
return "Account{" + "accountno=" + accountno + ", name=" + name + ", balance=" + balance + '}';
}
public void deposit(double amount){
balance = balance + amount;
}
void withdraw(double amount){
balance = balance-amount;
}
}
public static void AccountMenu() {
ArrayList<Account> a = new ArrayList();
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
switch (number) {
case 1: {
Account c = new Account();
System.out.println("Enter the Account no.");
c.accountno = in.nextInt();
System.out.println("Enter the name");
c.name = in.next();
System.out.println("Enter the Balance");
c.balance = in.nextDouble();
a.add(c);
break;
}
case 2: {
System.out.println("Account details are :");
for (Account b : a) {
System.out.println(b);
}
break;
}
case 3: {
System.out.println("Enter the account number");
int accountno = in.nextInt();
for (Account account : a) {
if (account.accountno == accountno) {
System.out.println(account);
}
}
break;
}
case 4:
System.out.println("Exit");
}
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu();
}
}
I am working a programming project from Java textbook that says:
The L&L bank can handle up to 30 customers who have savings accounts. Design and implement a program that manages the accounts. Keep track of key information and let each customer make deposits and withdrawals. Produce error messages for invalid transactions. Hint: You may want to base your accounts on the Account class from Chapter 4. Also provide a method to add 3 percent interest to all accounts whenever the method is invoked.
I am not certain on what the question is specifically asking but my guess is to allow and enable the user to add accounts, deposit, withdraw, add interest, get balance, and print the accounts being managed into an array. I am not entirely sure that I have to make an array but the whole chapter is on arrays.
My problem is that I am not sure how to enable the user to make an account
(EX: Account acct1 = new Account ("Ted Murphy", 72354, 102.56);),
to deposit money (EX: acct1.deposit (25.85);),
withdraw money (EX: acct3.withdraw (800.00, 0.0);),
add interest (EX: acct1.addInterest();),
or to print an array for all the accounts.
Here is the Account class found in the Java textbook with all the methods:
//********************************************************************
// Account.java Author: Lewis/Loftus/Cocking
//
// Represents a bank account with basic services such as deposit
// and withdraw.
//********************************************************************
import java.text.NumberFormat;
public class Accounts
{
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.035; // interest rate of 3.5%
private int acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Accounts (String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//-----------------------------------------------------------------
// Validates the transaction, then deposits the specified amount
// into the account. Returns the new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount is invalid.");
System.out.println (acctNumber + " " + fmt.format(amount));
}
else
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
amount += fee;
if (amount < 0) // withdraw value is negative
{
System.out.println ();
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
System.out.println ("Available: " + fmt.format(balance));
}
else
balance = balance - amount;
return balance;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
public double addInterestAll ()// I made this method myself but I am not sure if it is correct
{
balance += (balance * 0.03);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns the account number.
//-----------------------------------------------------------------
public int getAccountNumber ()
{
return acctNumber;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
}
}
Here is the main method that is under construction and I am not sure if I am on the right track:
import java.util.Scanner;
public class SixSix
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Input (0) to add account, (1) to deposit,");
System.out.println("(2) to withdraw, (3) to add interest, (4) to add interest to all");
System.out.println("(5) to get balance, (6) to get account number, (7) to print");
int input = scan.nextInt();
while (input == 0){
System.out.println("To create an account, please enter your name");
String name = scan.nextLine();
System.out.println("Please enter your account number");
int accNum = scan.nextInt();
System.out.println("Please Enter account balance");
double accBalance = scan.nextDouble();
//System.out.format
}
while (input == 1)
{
System.out.println("To deposit money to an account");
}
while (input == 2)
{
System.out.println("To withdraw money from an account");
}
while (input == 3)
{
System.out.println("To add Interest");
}
while (input == 4)
{
System.out.println("To add Interest to all");
}
while (input == 5)
{
System.out.println("To get balance");
}
while (input == 6)
{
System.out.println("To get account number");
}
while (input == 7)
{
System.out.println("Printing account");
}
}
}
It seems to me like you're on the right track. I'm inferring from the way the question (in the book) is phrased and the code that you've posted that the accounts don't already exist, in which case you need to allow the user of the system to create them. Then when altering an account, the user would first have to supply the account number so that you can identify the proper Accounts object.
I'm guessing that since the chapter was on arrays, it probably hasn't covered Maps yet (which would otherwise be a convenient way of associating account numbers to Accounts objects). If you use arrays, then having the account numbers range from 0 to 29 seems like a good idea.
Here's an example of how you could implement an AccountsManager class that helps you add and retrieve accounts from an array of accounts.
public class AccountsManager {
private Accounts[] accounts;
private final int capacity;
private int current;
public AccountsManager(int capacity) {
this.capacity = capacity;
accounts = new Accounts[capacity];
current = 0;
}
// returns the account number of the new account
// or -1 if no account could be made
public int addAccount(String name) {
if (current >= capacity) {
return -1;
}
accounts[current] = new Accounts(name, current, 0);
return current++;
}
public Accounts getAccount(int number) {
if (number >= current || number < 0) {
return null;
}
return accounts[number];
}
}
In the above, the capacity attribute is simply the size of the array, which is the maximum number of Accounts objects that can be created (this should be 30, according to the exercise). The current attribute (feel free to rename to something more informative!) keeps track of where in the array the next Accounts object should be created. This grows by one each time an account is added.
In your code, you could now do something like this:
AccountsManager manager = new AccountsManager(30);
// ...
if (input == 0) {
// Create new account
System.out.println("To create an account, please enter your name");
String name = scan.nextLine();
int accountNumber = manager.addAccount(name);
if (accountNumber == -1)
System.out.println("The bank can't handle any more accounts.");
else
System.out.println("Your account number is "+accountNumber);
} else if (input == 1) {
// Deposit money to account
System.out.println("What is your account number?");
int accountNumber = scan.nextInt();
// Check if account exists
if (manager.getAccount(accountNumber) == null) {
System.out.println("That account doesn't exist!");
} else {
System.out.println("How much do you want to deposit?");
double amount = scan.nextDouble();
manager.getAccount(accountNumber).deposit(amount);
}
}
Perhaps it might be preferable to create new methods in the AccountsManager class to make deposits etc, but this shows at least what the general structure could be like.
In my program, users enter values and those get stored in arrayList. ArryList objects are written into a file. I have used file-i/o, object-i/o stream for writing and readin in file.Now I want to perform addition and subtraction among the objects (int or double). That is withdrawing money from one account should be added with another account, and their value must be subtracted and added with the particular acount's amount. And finally I want that value must be updated so that it can print out and show the current status. How could I do that?
This is the main class:
public class BankApp_Assignment {
//static int numOfAcc = 0;
public static void main(String[] args) {
System.out.println("WELCOME TO OUR BANK!\n\n");
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
List<BankAccount> bankAccounts2 = new ArrayList<BankAccount>();
ReaderWriter rw=new ReaderWriter();
while (true) {
System.out.println("Choose your option:\n"
+ "1. Create new account\n"
+ "2. Deposit/withdraw\n"
+ "3. View One account\n"
+ "4. Deleting an account\n"
+ "5. View all the accounts\n"
+ "6. Return to menu\n");
System.out.println("*************\n"
+ "************");
option1 = sc.nextInt();
sc.nextLine();
//switch-case starts
switch (option1) {
case 1:
//create account
BankAccount bankAcc = new BankAccount();
System.out.println("Enter Full Name:");
bankAcc.setName(sc.nextLine());
System.out.println("Choose an Account Number:");
bankAcc.setAccNum(sc.nextInt());
System.out.println("Choose the initial amount:");
bankAcc.setInitiateAmount(sc.nextDouble());
//adding those into the arrayList
bankAccounts.add(bankAcc);
rw.writeToFile(bankAccounts);
System.out.println("-------------\n"
+ "-------------");
break;
case 2:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//First displaying the current accouns info
System.out.println("Name \tAccount No \tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\t\t.........\n"
+ "\t\t.........");
System.out.println("To transfer money within the bank accounts enter 1\n"
+ "To deposit/withdraw money in the same account enter 2");
option2 = sc.nextInt();
sc.nextLine();
//inner switch-case starts
switch (option2) {
case 1:
/*
BankAccount is the class for setter and getter
bankAccounts2 is the arrayList for reading objects from file
*/
bankAccounts2 = (List<BankAccount>) rw.readFromFile();
BankAccount fromAcc = null;
BankAccount toAcc = null;
System.out.println("Enter the account number you want to withdraw from:");
withdraw_accNum = sc.nextInt();
System.out.println("Enter the amount you want to withdraw:");
withdraw_amount = sc.nextDouble();
System.out.println("Enter the account number you want to deposit to:");
deposit_accNum = sc.nextInt();//the deposit amount is alwyas the same as withdraw_amount
//find the matching acc number:withdraw_accNum
for (BankAccount listItemsFirst : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsFirst.getAccNum() == withdraw_accNum) {
//store it
fromAcc = listItemsFirst;
break;
}
}
//find the matching acc number: deposit_accNum
for (BankAccount listItemsSec : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsSec.getAccNum() == deposit_accNum) {
//store it
toAcc = listItemsSec;
break;
}
}
//if the withdraw amount is bigger than the current balance
if (withdraw_amount > fromAcc.getInitialAmount()) {
System.out.println("Withdrawing Amount was bigger than the Initial amount.\nChoose the menu again. .");
break;
}
//subtracting and adding the withdrawn amount
fromAcc.setInitiateAmount(fromAcc.getInitialAmount() - withdraw_amount);
toAcc.setInitiateAmount(toAcc.getInitialAmount() + withdraw_amount);
System.out.println("DONE!\t print them out to see the current status.");
System.out.println("");
break;
case 2://deposit/withdraw money in the same accounts
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount fromAcc_SameAcc = null;
BankAccount toAcc_SameAcc = null;
System.out.println("Enter the account number you want to deposit or withdraw from:");
//read the accNum
depOrWithAccountNum = sc.nextInt();
System.out.println("Enter the amount (To withdraw enter a negative value)");
//read the amount
depOrWithAmount = sc.nextDouble();
//checking the matching account number in arrayList
for (BankAccount listItemsThird : bankAccounts2) {
if (listItemsThird.getAccNum() == depOrWithAccountNum) {
fromAcc_SameAcc = listItemsThird;
break;
}
}
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount()) {
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}
if (depOrWithAmount < 0) {//the amount is negative
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
} else {
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
}
break;
}
//inner switch-case ends
System.out.println("\n\n");
break;
case 3:
//View One account
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount viewOneAccountNum = null;
System.out.println("Enter the account number you want to see:");
viewOneAcc = sc.nextInt();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount viewOneAccountProperty : bankAccounts2) {
if (viewOneAccountProperty.getAccNum() == viewOneAcc) {
//viewOneAccountNum=viewOneAccountProperty;
viewOneAccountNum = viewOneAccountProperty;
System.out.println(viewOneAccountNum);
}
System.out.println("");
}
break;
case 4:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//BankAccount AccToDel = null;
//Deleting an account
Iterator<BankAccount> it = bankAccounts2.iterator();
System.out.println("Enter the account you want to delete:");
deleteAcc = sc.nextInt();
while (it.hasNext()) {
BankAccount next = it.next();
if (next.getAccNum() == deleteAcc) {
it.remove();
}
}
rw.writeToFile(bankAccounts2);
break;
case 5:
//View all the accounts/printing them out
bankAccounts2=(List<BankAccount>)rw.readFromFile();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\n\n");
break;
case 6:
//Quit
return;
}
//switch-case ends
}
}
}
ReaderWriter:
public class ReaderWriter{
public void writeToFile(List<BankAccount> accounts){
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(accounts);//take the arrayList
oos.flush();
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<BankAccount> readFromFile(){
List<BankAccount>readData=null;
try {
FileInputStream fis=new FileInputStream("C:\\Users\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//make an arrayList to get those object back
//arrayList
readData=(List<BankAccount>)ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
//return readData;
return readData;
}
}
BankAccount:
package bankapp_assignment;
import java.io.Serializable;
public class BankAccount implements Serializable{
private String name;
private int accNum;
private double initiateAmount;
//constructor
public BankAccount() {
this.name = null;
this.accNum = 0;
this.initiateAmount = 0;
}
public void setName(String name) {
this.name = name;
}
public void setAccNum(int accNum) {
this.accNum = accNum;
}
public String getName(String name){
return name;
}
public int getAccNum() {
return accNum;
}
public void setInitiateAmount(double initiateAmount) {
this.initiateAmount = initiateAmount;
}
public double getInitialAmount(){
return initiateAmount;
}
#Override
public String toString() {
return name + "\t\t" + accNum + "\t\t" + initiateAmount;
}
}
you should refactor whole main method. If I were you, I would use
main only to lunch program, rest process in other methods. This way you would be able to use class fields all over program, and divide code into many methods.
You should divide main beetween other methods, to at least method
per action, exemple:
case 1:
createAccount();
break;
(...)
public void createAccount(){
code from your swich case 1
}
etc. You can still use swich control, but should replece logic code to another method.
When i run your code, input/output didn't work. Were you able to
save/load file? I had to chage:
File file = new File("//file path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput oos = new ObjectOutputStream(fos);
Same with input. Then it worked.
Now, we will try to deal with operation on BankAccounts from files. I change a little bit your code from case2/case2: deposit/withdraw, lets look at it:
bankAccounts2 = rw.readFromFile(); // loading list from file
BankAccount edited = new BankAccount(); // creating new object
System.out.println("Enter the account number you want to deposit or withdraw from:");
double input = sc.nextInt(); // you don't need to create new variable every time you take input form user
for(BankAccount account : bankAccounts2){ // every account in list
if(account.getAccNum() == input) edited = account; // if acccNum match, give edited reference to chosen account
}
System.out.println("Enter the amount (To withdraw enter a negative value)");
input = sc.nextDouble();
double result = edited.getInitialAmount() + input; // result of operation
if(result < 0){ // check if there is enough money on account
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}else{
edited.setInitiateAmount(result); // if there is, set new value
}
rw.writeToFile(bankAccounts2); // save file
You can implement another operation in similar style. But still, you should consider dividing main into other methods, adding class fields, etc.
EDIT:
For question in comments.
Because you use positive numbers for deposit, and negative numbers for withdraw, the operation on initialAmount will be always the same: initialAmount + input (if negative, is will subtract from amount), so you can treat it like an one case in your code. In your code you use this line twice:
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
so you already could merge both cases into one, to avoid unnecessary repetitions. So only case when action will differ, is when there is not enough money on a account, you check it by:
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount())
but i think i will not work, because in withdraw operation depOrWithAmount is in negative numbers, so it will always be smaller than fromAcc_SameAcc.getInitialAmount(). You can use:
if (depOrWithAmount < 1 - fromAcc_SameAcc.getInitialAmount())
(but i think it is not too readable) or:
if (Math.abs(depOrWithAmount) > fromAcc_SameAcc.getInitialAmount()){}
to compare absolute value of input with initialAmout. However i used:
double result = edited.getInitialAmount() + input;
if(result < 0){...}
because it gives me result variable, which I can reuse if there is enough money, to gives new value to initialAmount. And if result is negative, it means that withdraw amount was bigger than initialAmount, so ther is no enough monay to withdraw.
I hope you found something useful in my post.
I have a really long problem. I am creating a bank account and setting the balance to 0. If the user chooses to withdraw or deposit money to the account, the balance never changes. I choose to show the balance and it still says 0. This is probably a no brainer but I am spent right now. Here is my long code(The switch statement is in my main class and the methods are in an object class):
public class MyProgram2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
String menu, outputString, poo;
int option = 1;
int id = 0;
double balance = 0, amount = 0;
Account acc = new Account();
menu ="\n\t1 Create Account and ID" +
"\n\t2 Check balance" +
"\n\t3 Withdraw" +
"\n\t4 Deposit" +
"\n\t5 Get account ID" +
"\n\t6 Display Account Info" +
"\n\t0 Quit\n\n\n";
System.out.println(menu);
System.out.println("\tEnter your selection: ");
option = scan.nextInt();
while (option != 0) {
switch (option) {
case 1: //Create an account and set ID
System.out.print("Enter Your Account ID to create account:\t");
id = input.nextInt();
System.out.println("Account created!");
break;
case 2: //check balance
acc.checkBalance(balance);
break;
case 3: //withdraw money
acc.withdraw(balance, amount);
break;
case 4: //deposit money
acc.deposit(balance, amount);
break;
case 5: //get account id
acc.getID(id);
break;
case 7: //display account info
System.out.print("option 7");
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}
System.out.println(menu);
System.out.print("\tEnter your selection: ");
option = scan.nextInt();
}
And these are the methods I am calling:
public class Account{
Scanner input = new Scanner (System.in);
public Account(){
}
public void getID(int id){
System.out.println("Your account ID is:\t" + id);
}
public void checkBalance(double balance){
System.out.println("Your balance is:\t$" + balance);
}
public double withdraw(double amount, double balance){
System.out.println("How much do you want to withdraw?:\t$");
amount = input.nextDouble();
balance -= amount;
return balance;
}
public double deposit(double amount, double balance){
System.out.println("How much do you want to deposit?:\t");
amount = input.nextDouble();
balance += amount;
return balance;
}
public void getAccountInfo(int id, double balance){
}
}
The variable double balance cannot be passed as a reference. It does a copy so when you try to manipulate it, it won't affect the original that you pass as an argument. You need to update the value using the return value that you have in the function.
In order to make it work, you should do:
case 4: //deposit money
// note here that you need to update the balance variable using the return value that
// you put in the function
balance = acc.deposit(balance, amount);
break;
Note: Your design separating the balance from the Account class is not ideal per #Psyrus's answer. You should keep the balance as part of the Account class. The reason being that balance is part of the account and if your program grows to handle multiple accounts (just for the sake of examples), separating the variable balance from the account would create maintenance headache (imagine that with two instances of Account, you will have balance1 and balance2 variables (or whatever you will call it) in MyProgram2, the main application). While I gave the cause of your problem in regards of variable passing, you should refactor your code to follow #Psyrus suggestion.
You have your whole Account class set up but without the actual balance variable inside it. Move that variable from your program to your class and it should work. Upon looking further, you have kind of jumbled up bits between the two so do this:
public class MyProgram2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
String menu, outputString, poo;
int option = 1;
int id = 0;
Account acc = new Account();
menu ="\n\t1 Create Account and ID" +
"\n\t2 Check balance" +
"\n\t3 Withdraw" +
"\n\t4 Deposit" +
"\n\t5 Get account ID" +
"\n\t6 Display Account Info" +
"\n\t0 Quit\n\n\n";
do {
System.out.println(menu);
System.out.println("\tEnter your selection: ");
option = scan.nextInt();
switch (option) {
case 1: //Create an account and set ID
System.out.print("Enter Your Account ID to create account:\t");
id = input.nextInt();
System.out.println("Account created!");
break;
case 2: //check balance
acc.checkBalance();
break;
case 3: //withdraw money
acc.withdraw();
break;
case 4: //deposit money
acc.deposit();
break;
case 5: //get account id
acc.getID(id);
break;
case 7: //display account info
System.out.print("option 7");
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}
} while (option != 0);
}
}
public class Account{
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in); double balance = 0;
public Account(){
}
public void getID(id){
System.out.println("Your account ID is:\t" + id);
}
public void checkBalance(){
System.out.println("Your balance is:\t$" + balance);
}
public double withdraw(){
System.out.println("How much do you want to withdraw?:\t$");
double amount = input.nextDouble();
balance -= amount;
}
public double deposit(){
System.out.println("How much do you want to deposit?:\t");
double amount = input.nextDouble();
balance += amount;
return balance;
}
public void getAccountInfo(int id, double balance){
}
}
That is one way of doing it, but like I say, your design is a bit of a cross between classes. You should try to keep all properties for an object within that class and create functions for that class to obtain / modify the properties. Printing to the user should be contained in the class responsible for giving the user the interface.
Edit: Oops forgot the while at the end of the do while loop...
You just need to modify the instance you created like this:
public double deposit(){
System.out.println("How much do you want to deposit?:\t");
this.amount = input.nextDouble();
this.balance += amount;
return balance;
}
The this keyword refers to the object that is calling this method in this case acc, so this.amount will modify the amount for that instance.
In your current code, you are just modifying the local variables.
You also need to update your Account class to have the amount and balance attributes:
public class Account{
Scanner input = new Scanner (System.in);
double balance = 0, amount = 0;