//*******************************************************
// Account.java
//
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
//*******************************************************
import java.util.Random;
public class Account
{
private double balance;
private String name;
private long acctNum;
//----------------------------------------------
//Constructor -- initializes balance, owner, and account number
//----------------------------------------------
public Account(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//----------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}
//----------------
//Track how many accounts
//----------------
private static int numAccounts=0;
{
numAccounts++;
}
public static int getNumAccounts()
{
return numAccounts;
}
//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//----------------------------------------------
// Returns balance.
//----------------------------------------------
public double getBalance()
{
return balance;
}
// Get name of account
public String getName()
{
return name;
}
//----------------------------------------------
// Returns account number.
//----------------------------------------------
public long getAcctNumber()
{
return acctNum;
}
//----------------
//Void and close the accounts
//----------------
public void close()
{
balance = 0;
name += "CLOSE";
numAccounts--;
}
//----------------
//Consolidating accounts
//----------------
public static Account consolidate(Account acct1,Account acct2)
{ Account newAccount=null;
if((acct1.getName()).equals(acct2.getName()))
if(acct1.getAcctNumber()!=acct2.getAcctNumber())
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
Random generator = new Random();
acctNum= generator.nextInt();
acct1.close();
acct2.close();
}
else
System.out.println("Not allow,same account number");
else
System.out.println("Can't use other people account");
return newAccount;
}
//----------------------------------------------
// Returns a string containing the name, account number, and balance.
//----------------------------------------------
public String toString()
{
return "Name: " + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
Please look at the //consolidate section. What I'm trying to do is, consolidate acct1 and acct2 into one new account, with the restrictions that is acct1 and acct2 has to has the same name, acct1 and acct2 account number has to be different from each other, and if those are met, create a new account with a new balance from the two old account, keep the same name and also randomly generate a new account number. Is there something missing in my code? It wont compile. These are errors i got
Account.java:95: ')' expected
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
^
Account.java:95: illegal start of expression
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
^
String owner should just be acct1.getName() or whatever function retrieves the name.
Also, the line acctNum = generator.nextInt(); will fail as acctNum isn't defined in that context. Furthermore, you don't set the account number of newAccount to be this acctNum variable.
I suggest you change it to this:
newAccount.setAcctNumber(generator.nextInt());
The compile error at the line
newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner)
is because String owner is a declaration that should be used in a method signature, as you did above. When you actually make a call to the constructor, though, you need to send a String parameter in.
The compiler is complaining because what you are actually doing at this line is declaring a String variable named owner. Java won't allow that in a method call.
Finbarr is right; use the method to get the name of the account instead.
Related
How do i pass a specific content of an index of an arraylist to a method? (i'm not sure of the correct terms)
This is what i'm trying to achieve:
Get user input for the amount to withdraw from the first account, then print the balance. Repeat
the same for deposit.
This is my class code:
import java.util.Date;
public class Account2 {
private int id = 0;
private double balance = 0;
private static double annualInterestRate = 0;
private Date dateCreated;
public Account2() {
id = 0;
balance = 0;
}
public Account2(int id, double balance) {
this.id = id;
this.balance = balance;
}
// getters and setters (omitted for brevity)
public double withdraw(int amount) {
return balance - amount;
}
public double deposit(int amount) {
return balance + amount;
}
}
This is the Test class:
import java.util.ArrayList;
import java.util.Scanner;
public class TestAccount2 {
public static void main(String[] args) {
//Account2 acc = new Account2();
Account2.setannualInterestRate(4.5);
//Creates an ArrayList of 3 Account objects
ArrayList<Account2> list = new ArrayList<Account2>();
for(int i=1; i<4; i++) {
//USE ARRAYLIST SYNTAX
list.add(new Account2(i+100, i*10000 ));
}
//print all the content of ArrayList
for(Account2 auto : list) {
System.out.println(temp);
}
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
}
}
This is where i'm stuck:
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
This is the method i'm trying to pass the index of arraylist into:
public double withdraw(int amount) {
return balance - amount;
}
thank u.
You need to invoke those methods specifying the instance of the account you want to alter. For example, if you want to withdraw from the first account of the ArrayList, you'll write something like:
list.get(0).withdraw(amount);
You can do the same for the deposit method.
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 am trying to call a getName and getBalance method from another class called Account in my printbalances method in class bank. but it is not working it prints null after inputing customer and balance. can someone explain why and how to fix it? I can honestly say I don't know why it is not working.
Here is the class that is calling it:
class Bank {
ArrayList<Account> accounts = new ArrayList<>();
Scanner input = new Scanner(System.in);
Scanner q;
String name;
double balance;
private Account account = new Account(name, balance);
public void enterCustomers() {
System.out.println("Enter customer names or press q to quit entering names: ");
while (true) {
String name;
double balance;
System.out.print("Enter a customer name: ");
name = input.next();
if ("q".equals(name)) { //tried using == to break but wouldnt work so tried .equals since comparing strings and works
break;
}
System.out.print("Enter the opening balance : ");
balance = input.nextDouble();
accounts.add(new Account(name, balance));
}
}
public void printBalances() {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
System.out.println(account.getName() + account.getBalance());
}
and here is the classs where the get methods are stored:
class Account {
private String name;
private double balance;
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
//public void setName(String name) {
// this.name = name;
//}
public double getBalance() {
return balance;
}
//public void setBalance(double balance) {
// this.balance = balance;
//}
public void deposit(double amount) {
balance += amount;
}
public void withdrawal(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println(" Insufficient Balance. ");
}
}
}
The output it gives me is this:
Enter customer names or press q to quit entering names:
Enter a customer name: john
Enter the opening balance : 200
Enter a customer name: mike
Enter the opening balance : 2
Enter a customer name: q
==========================
Opening account balance
==========================
Customer Balance
==========================
null0.0
(1)deposit (2)withdraw (0)quit
I dont know why null 0.0 appears and can someone explain why?
Right now you are initializing account like this:
private Account account = new Account(name, balance);
But here name and balance are not initialized, so they are null and zero respectively by default. It looks more like you want to print the name and balance of a specific Account object, so I would pass it as an argument to printBalances:
public void printBalances(Account account) {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
System.out.println(account.getName() + " : " + account.getBalance());
}
Or if you wanted to print every balance in the accounts ArrayList:
public void printBalances() {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
for(Account account : accounts) {
System.out.println(account.getName() + " : " + account.getBalance());
}
}
Are there any more references to account?
You are likely overriding it at some point because it has a name of null and a balance of 0.0
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.
//*******************************************************
// FlexibleAccount.java
//
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
//*******************************************************
import java.util.Random;
public class FlexibleAccount
{
private double balance;
private String name;
private long acctNum;
//----------------------------------------------
//Constructor -- initializes balance, owner, and account number
//----------------------------------------------
public FlexibleAccount(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
public FlexibleAccount(double initBal, String owner, double number)
{
Random generator = new Random();
balance = initBal;
name = owner;
number=generator.nextDouble();
this.acctNum= number;
}
public FlexibleAccount(String owner)
{
balance = 0;
name=owner;
Random generator = new Random();
number=generator.nextDouble();
this.acctNum= number;
}
//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//----------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}
public void withdraw(double amount,int fee)
{
if(balance>=amount)
balance-= amount+fee;
else
System.out.println("Insufficient funds");
}
//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//----------------------------------------------
// Returns balance.
//----------------------------------------------
public double getBalance()
{
return balance;
}
//----------------------------------------------
// Returns a string containing the name, account number, and balance.
//----------------------------------------------
public String toString()
{
return "Name: " + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
This is what i have and I'm trying to overload the FlexibleAccount 3 times as follow
public FlexibleAccount (double initBal, String owner, long number) – initializes the balance, owner, and account number as specified
public FlexibleAccount (double initBal, String owner) – initializes the balance and owner as specified; randomly generates the account number.
public FlexibleAccount (String owner) – initializes the owner as specified; sets the initial balance to 0 and randomly generates the account number.
When I compiled i get these error
FlexibleAccount.java:31: possible loss of precision
found : double
required: long
this.acctNum= number;
^
FlexibleAccount.java:39: cannot find symbol
symbol : variable number
location: class FlexibleAccount
number=generator.nextDouble();
^
FlexibleAccount.java:40: cannot find symbol
symbol : variable number
location: class FlexibleAccount
this.acctNum= number;
^
How do I fix this and is this the right way to overload?
Just like previous question - there is no such variable number when you write acctNum = number; in public FlexibleAccount(String owner):
public FlexibleAccount(String owner)
{
balance = 0;
name=owner;
Random generator = new Random();
number=generator.nextDouble(); << number is not declared
this.acctNum= number;
}
EDIT:
This is your 2nd constructor:
public FlexibleAccount(double initBal, String owner, double number)
{
Random generator = new Random();
balance = initBal;
name = owner;
number=generator.nextDouble();
this.acctNum= number;
}
For some reason you declare it with 3 arguments although you wrote you want it to be receive only 2 arguments -
public FlexibleAccount (double
initBal, String owner) – initializes
the balance and owner as specified;
randomly generates the account number.
I guess you wanted to have the variable number... it should be more something like that:
public FlexibleAccount(double initBal, String owner)
{
Random generator = new Random();
balance = initBal;
name = owner;
this.acctNum= generator.nextLong();
}
Now as you said in the prev. question this is a homework, so I won't add to that. Read the answers and comments you got until now and work it up.