How to print balance in a banking program (Java) [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have created a Java program for banking, which allows the user to deposit funds, withdraw funds, and check their balance.
However, I would like to be able to print the convToString data (name, accNo, balance) whenever the getBalance() command is called. This would be much more effective than having to type System.out.println(JohnSmith.convToString()+"\n") each time I want to print the account information.
Any advice on how best to clean my code up and make this happen?
My full source code follows...
package week1src;
public class BankAccount {
private String name;
private int accNo;
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount)
{
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a)
{
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Return a String containing all the information of the account based on account name input
--------------------*/
public String convToString( )
{
return("Account name: " + this.name + ", Account number: " + this.accNo + ", Available balance: " + "£" + this.balance);
}
/* --------------------
Method to deposit funds by adding "amount" to balance
--------------------*/
public void deposit(double amount) {
if (amount <= 0) {
// returns an error message is value entered is negative
System.err.println("Cannot deposit negative amounts. Please enter a different amount.");
}
else {
this.balance += amount;
System.out.format("£%.2f has been deposited\n", amount);
}
}
/* --------------------
Method to withdraw funds by subtracting "amount" from balance
--------------------*/
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.format("£%.2f has been withdrawn\n", amount);
}
else { // returns an error message if withdrawal with put account balance below 0
System.err.println("Transaction cancelled due to insufficient funds. Check balance or deposit funds.");
}
}
/* --------------------
Method used to display account balance
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
}
package week1src;
public class BankMain {
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount("John Smith", 1, 00); // create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount("David Jones", 2, 1000); // create an account object (acc name, acc no, opening balance)
System.out.println(JohnSmith.convToString()+"\n"); // will display acc name, acc number, and current balance (£0)
JohnSmith.deposit(100); // deposit £100
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10); // deposit £10
JohnSmith.withdraw(25); // withdraw £25
JohnSmith.withdraw(90); // will return error as balance will go <0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw £70
System.out.println(JohnSmith.convToString()+"\n"); // will display acc name, acc number, and current balance (£15.00)
}
}

It can be achieved like this:
BankAccount.java:
public class BankAccount {
private String name;
private int accNo;
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount) {
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a) {
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Method to deposit funds by adding "amount" to balance
--------------------*/
public void deposit(double amount) {
if (amount <= 0) {
// returns an error message is value entered is negative
System.err.println("Cannot deposit negative amounts. Please enter a different amount.");
} else {
this.balance += amount;
System.out.format("£%.2f has been deposited\n", amount);
}
}
/* --------------------
Method to withdraw funds by subtracting "amount" from balance
--------------------*/
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.format("£%.2f has been withdrawn\n", amount);
} else { // returns an error message if withdrawal with put account balance below 0
System.err.println(
"Transaction cancelled due to insufficient funds. Check balance or deposit funds.");
}
}
/* --------------------
Method used to display account balance
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
public void printAccountInfo() {
System.out.println(this);
}
#Override
public String toString() {
return "Account name: " + this.name + ", Account number: " + this.accNo
+ ", Available balance: " + "£" + this.balance;
}
}
BankMain.java:
package your.package.here;
public class BankMain{
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount("John Smith", 1,
0); // create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount("David Jones", 2, 1000); // create an account object (acc name, acc no, opening balance)
JohnSmith.printAccountInfo();
JohnSmith.deposit(100); // deposit £100
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10); // deposit £10
JohnSmith.withdraw(25); // withdraw £25
JohnSmith.withdraw(90); // will return error as balance will go <0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw £70
JohnSmith.printAccountInfo();
}
}
It seems reasonable to create a separate reusable printing method, that will do all what you need. And instead of creating your convToString method, you can just override toString and then use it in a way that I've posted. This is built in java mechanism that do exactly what you need.
Tricky thing here is when you're calling System.out.println(this); default behavior is to call toString method on that object that you've passed to the System.out.println method.
And here is the magic happens, you just override toString, and then call System.out.println on your object instance. It will then take your instance and call your overrided toString on that.
Please, have a look.

Related

How to transfer funds from one account to another in java, using user input for each desired account, and amount to transfer

I am trying to create and execute a method which allows the user to choose an account from which and an account to which the user wants to transfer an amount, which the user also chooses. But, I don't know how to get user input asking from and to which class they want to transfer funds to.
I've tried using the Scanner method but I can't get it to work.
Here is the code, it's the same as the code beneath this but this is easier to view imo: https://gist.github.com/KamronKelley/32d9a40c285e501f64cf73fa28bf87b5
package banking;
public class Account {
String name;
double balance;
public Account() {
name = "";
balance = 0.0;
}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public void addFunds(double addedAmount) {
balance = balance + addedAmount;
}
public void withdraw(double withdrawnAmount) {
balance = balance - withdrawnAmount;
}
public void transfer(double amount, Account from, Account to) { //here is the transfer method, if i can improve this or alter it in order to make it easier to run using user input from the main file, let me know
if(from.balance >= amount){
from.balance = from.balance - amount;
to.balance = to.balance + amount;
System.out.println("Funds successfully transfered.");
} else {
System.out.println("Insufficient funds");
}
}
}
package banking;
import java.util.Scanner;
public class BankSimulator {
public static void main(String[] args) {
System.out.println("Hello and welcome to the banking system. Please enter a name to create an account, no spaces: ");
Scanner scan = new Scanner(System.in);
Account a1 = new Account();
a1.setName(scan.next());
System.out.println("Account name: " + a1.getName());
int count = 0;
while(count == 0) {
System.out.println("What would you like to do next?" + "\n" +
"Change account name: press 1" + "\n" +
"See account name: press 2" + "\n" +
"Check balance: press 3" + "\n" +
"Add money to balance: press 4" + "\n" +
"Withdraw money from balance: press 5" + "\n" +
"Exit program: press 7: " + "\n" +
"To transfer funds between accounts: press 6");
int toDo = scan.nextInt();
if(toDo == 1) {
System.out.println("Enter new account name: ");
a1.setName(scan.next());
System.out.println("Account name: " + a1.getName());
}
else if(toDo == 2) {
System.out.println("Account name: " + a1.getName());
}
else if(toDo == 3) {
System.out.println("Current balance: $" + a1.getBalance());
}
else if(toDo == 4) {
System.out.println("Desired amount to add: $");
a1.addFunds(scan.nextDouble());
System.out.println("Money successfully added to balance.");
}
else if(toDo == 5) {
System.out.println("Desired amount to withdraw: $");
a1.withdraw(scan.nextDouble());
System.out.println("Money successfully withdrawn from balance.");
}
else if(toDo == 6) {
System.out.println("Enter the account you would like to transfer money from:");
String fromAccount = scan.next();
System.out.println("Enter the account you would like to transfer money to:");
String toAccount = scan.next();
System.out.println("Enter the amount of money you would like to transfer: $");
double moneyToTransfer = scan.nextDouble();
//this is what i need help with, I don't know what to do with these three things, and since the first two arent accounts, i cant run the transfer method on them
}
else if(toDo == 7) {
System.out.println("Thank you for using our banking system. Until next time.");
count = 1;
}
}
}
}
I can't do anything with the user input because I need the desired accounts in order to run the transfer method with them.
You need to keep track of all the accounts in a List or maybe a Map. Then you using the user input you search and retrieve the desired accounts. Also I don't think you need the transfer method in the Account object you can just use withdraw and addFunds from the main, or maybe have it like a static method. Also I think you will need a few additional operations, like create new account and maybe a login that will just change the active account. Currently you only have 1 account which is a1 so it makes no sense to transfer anything.
I think I understand what you are saying, I already checked your code but I think there's a bit of redundant code in there, like your "Account from". If you are the owner of an account and you are transferring to another do you need to specify your account number? You understand?
Secondly, it's best your multiple ifs and else-ifs to switch case statements.
class bankAccount {
String name;
private double balance;
private final long acctNum = ThreadLocalRandom.current().nextLong(100000000, 999999999);
public bankAccount(String name, double balance) {
this.name = name;
this.balance = balance;
System.out.println("HELLO " + name + ", Your account number is: " + acctNum);
}
public void setName(String name) {
this.name = name;
}
public void addFunds(int amount) {
this.balance += amount;
}
public void withdrawFunds(int amount) {
this.balance -= amount;
}
public double getBalance() {
return balance;
}
public long getAcctNum() {
return acctNum;
}
public void transfer(bankAccount name, double amount) {
if(this.balance >= amount) {
name.balance += amount;
this.balance -= amount;
System.out.println("Transaction Successful");
}
else {
System.err.println("Insufficient Funds!");
}
}
}
class BankSimulator {
static bankAccount John = new bankAccount("John", 50000);
static bankAccount James = new bankAccount("James", 3000);
public static void main(String[] args) {
John.transfer(James, 300);
System.out.println("John's new balance is "+ John.getBalance());
System.out.println("James' new balance is "+ James.getBalance());
}
}
since you'll be making use of another account, you should create two instances of the Account class, this would clarify the ambiguity between which accounts to transfer to.
Essentially all I did was create the Account class, created an instance named John(John's Account) and create an instance named James (James' Account), so now, There you go with two account classes, with different fields but similar methods (getBalance(), transfer(), getAcctNum(), addFunds(), withdrawFunds()).
I Hope this is what you need, Happy Coding!
I suggest you create dummy data (existing) Account first:
List<Account> accountList = new ArrayList<>();
Account acct1 = new Account("tester1", 100.0);
Account acct2 = new Account("tester2", 100.0);
accountList.add(acct1);
accountList.add(acct2);
Add constructor for Account for easier adding of Accounts:
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
Store new account account in list:
accountList.add(a1);
For your procedure for "(toDo == 6)" which is for transfer:
Check first if accountList has at least 2 accounts because it won't make sense if there's only 1 account.
else if (toDo == 6) {
if (accountList.size() > 2) {
System.out.println("Enter the account you would like to transfer money from:");
String fromAccount = scan.next();
System.out.println("Enter the account you would like to transfer money to:");
String toAccount = scan.next();
System.out.println("Enter the amount of money you would like to transfer: $");
double moneyToTransfer = scan.nextDouble();
for (Account account : accountList) {
if (account.getName().equals(fromAccount)) {
account.withdraw(moneyToTransfer);
}
if (account.getName().equals(toAccount)) {
account.addFunds(moneyToTransfer);
}
}
} else
System.out.println("Cannot transfer.");
}
Also consider if the account actually exists, so add additional checking. Hope this helps!
I know this conversation was from awhile ago, however, must mention to definitely Not use a static method as anthony suggested in this type of situation because a static method can only access static variables and methods.

Combining two accounts [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is a homework assignment. I need to consolidate the two accounts (acct2 and acct3) and produce a third one with the same name, different account number and $200. I also have to close the first two accounts. That is not really the issue though. I can get everything to work fine if I do not declare public static Account accountConsolidate(Account acct1, Account acct2) as a static method, and just create an object in the main. This does not work though because I am required to declare this method as static. Also, if I do declare it as static I can get the proper return value in the if(acct1.name.equalsIgnoreCase(acct2.name) && acct1.acctNum != acct2.acctNum) if I exclude the
`&& acct1.acctNum != acct2.acctNum
other wise it will return null ("These two accounts are not able to be consolidated. Please check the criteria again", not sure why.
Any help would be great. Thanks
import java.util.Random;
public class Account
{
private static int numAccounts = 0;
private double balance;
private static String name;
private static double acctNum;
static Random gen = new Random();
//-------------------------------------------------
//Constructor -- initializes balance, owner, and account number
//-------------------------------------------------
public Account(double initBal, String owner, double number)
{
balance = initBal;
name = owner;
acctNum = number;
numAccounts++;
}
public Account(double initBal, String owner)
{
balance = initBal;
name = owner;
acctNum = Math.abs(gen.nextDouble());
numAccounts++;
}
public Account(String owner)
{
balance = 0;
name = owner;
acctNum = Math.abs(gen.nextDouble());
numAccounts++;
}
//-------------------------------------------------
// 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, double fee)
{
if (balance >= amount)
{
balance -= amount;
balance -= fee;
}
else
System.out.println("Insufficient funds");
}
public String getName()
{
return name;
}
public double getNum()
{
return acctNum;
}
//-------------------------------------------------
// Adds deposit amount to balance.
//-------------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//-------------------------------------------------
// Returns balance.
//-------------------------------------------------
public double getBalance()
{
return balance;
}
// Static method to keep track of incrementing Account
public static int getNumAccounts()
{
return numAccounts;
}
// Close the account
public void close()
{
balance = 0;
name = "CLOSED";
numAccounts--;
}
// Consolidate accounts
public static Account accountConsolidate(Account acct1, Account acct2)
{
if(acct1.name.equalsIgnoreCase(acct2.name) && acct1.acctNum != acct2.acctNum)
{
Account Account2 = new Account(0, acct1.name);
Account2.balance = acct1.getBalance() + acct2.getBalance();
acctNum = Math.abs(gen.nextDouble());
acct1.close();
acct2.close();
return Account2;
}
else
{
System.out.println("These two accounts are not able to be consolidated. Please check the criteria again");
return null;
}
}
//-------------------------------------------------
// Returns a string containing the name, account number, and balance.
//-------------------------------------------------
public String toString()
{
return "Name:" + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
//************************************************************
//TestAccounts1
//A simple program to test the numAccts method of the
//Account class.
//************************************************************
import java.util.Scanner;
public class TestAccount1
{
public static void main(String[] args)
{
String name1;
String name2;
String name3;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the name for account 1: ");
name1 = scan.nextLine();
Account acct1 = new Account (100, name1);
System.out.println(acct1);
System.out.println("Now there are " + Account.getNumAccounts() + " accounts");
System.out.println("");
System.out.print("Please enter the name for account 2: ");
name2 = scan.nextLine();
Account acct2 = new Account (100, name2);
System.out.println(acct2);
System.out.println("Now there are " + Account.getNumAccounts() + " accounts");
System.out.println("");
System.out.print("Please enter the name for account 3: ");
name3 = scan.nextLine();
Account acct3 = new Account (100, name3);
System.out.println(acct3);
System.out.println("Now there are " + Account.getNumAccounts() + " accounts");
System.out.println("");
acct1.close();
System.out.println("");
System.out.println("There are now " + Account.getNumAccounts() + " accounts");
System.out.println("Accounts consolidated");
System.out.println(Account.accountConsolidate(acct2, acct3));
}
}
Your account numbers are randomly generated but the accNum is static. So every account will have the created account number of the last account. So acct1.acctNum != acct2.acctNum will always be false.
Your account name is static as well, so each account will have the account name of the last created account.
After you changed this read your compiler errors. It will tell you what to do next. Think about which variables of which object you will modify. Like acctNum = Math.abs(gen.nextDouble()); will not set the account number of your consolidated account Account2.

Code returning node instead of value of subclass

I am very new to programming and am having a problem with some code for a class I am taking. I need to make a bank account class that returns the balance, adds a deposit, makes a withdrawal, and prints a statement with the current interest rate. I am stuck trying to get the the main class to return the values of the savings account class. Instead it returns the node value and I can't figure out what I a doing wrong. Any help would be appreciated. Code is below.
FinalExam.java
import java.io.*;
import java.util.Scanner;
public class FinalExam
{
SavingsAccount savings;
static String name;
static double balance;
public static void main (String[] args) throws NegativeAmountException, InsufficientFundsException {
double amount = 0;
SavingsAccount savings = null;
Scanner keyboard = new Scanner(System.in);
try
{
savings = new SavingsAccount("Penny Saved", 500.00, .05);
System.out.println(savings);
}
catch(NegativeAmountException e)
{
System.out.println("NegativeAmountException: " + e.getMessage());
System.exit(1);
}
System.out.println(savings);
Scanner input = new Scanner(System.in);
System.out.print("Enter your deposit amount: ");
amount = keyboard.nextDouble();
System.out.println(savings);
System.out.println("Enter your withdrawal amount: ");
amount = keyboard.nextDouble();
savings.postInterest();
System.out.println(savings);
}
}
BankAccount.java
import java.util.InputMismatchException;
import java.util.Scanner; //Import for scanner
public class BankAccount {
public String name;
public double balance;
//set name and balance
// make sure balance is not negative
// throw exception if balance is negative
public BankAccount(String name, double balance)throws NegativeAmountException {
if (balance < 0)
throw new NegativeAmountException("Cannot create a BankAccount with a negative balance");
}
public BankAccount(String name)
throws NegativeAmountException
{
// set name and use 0 balance
name = null;
balance = 0;
}
public void deposit(double amount) throws NegativeAmountException {
if (amount < 0)
throw new NegativeAmountException("Cannot deposit a negative amount: " + amount);
balance = balance + amount;
}
public void withdraw(double amount) throws InsufficientFundsException, NegativeAmountException {
if (amount > balance)
throw new InsufficientFundsException("Cannot withdraw more than the current balance of this BankAccount");
if (amount < 0)
throw new NegativeAmountException("Cannot withdraw a negative amount: " + amount);
balance = balance - amount;
}
public double getBalance() {
return balance;
}
// print bank statement including customer name
// and current account balance
public void printStatement() {
System.out.println("BankAccount owned by: " + name + " balance: $" + balance);
}
}
SavingsAcount.java
public class SavingsAccount extends BankAccount
{
double interest;
public SavingsAccount(String name, double balance, double interest) throws NegativeAmountException {
super(name, balance);
}
public double getInterest()
{
return interest;
}
public void postInterest() {
balance = balance + ((balance * interest)/12);
}
public void printStatement() {
super.printStatement();
System.out.println("Account for " + name + " Saved" + balance + " balance: $" + "Current Interest Rate is" + interest);
}
}
I know the last part of the FinalExam.java is incomplete, but I am trying to get the statement to print out before I move on the other issues. Any suggestions would be appreciated.
I am stuck trying to get the the main class to return the values of the savings account class. Instead it returns the node value and I can't figure out what I a doing wrong.
Your problem is that you are calling
savings = new SavingsAccount("Penny Saved", 500.00, .05);
System.out.println(savings);
println automatically calls the toString method on its argument. Since you didn't #Override the toString method of SavingsAccount, it prints what you call the "node value".
Your SavingsAccount has a method
public void printStatement()
which seems to print the information you want. So call it instead of println.
In the FinalExam.java class you suppose to print the values of the SavingsAccount.java class but you are getting the address. This id because in FinalExam.java class System.out.println(savings); rather than that yous should use like savings.printStatement();. May be I am not wrong what I guess..
When you print an object using System.out.println(savings) method, it internally calls the toString() method on that object. You need to implement the toString() method for both the classes SavingsAccount and BankAccount.
For the SavingsAccount use this:
#Override
public String toString() {
return "SavingsAccount{" +
super.toString() +
", interest=" + interest +
'}';
}
For BankAccount use this:
#Override
public String toString() {
return "BankAccount{" +
"name='" + name + '\'' +
", balance=" + balance +
'}';
}
Currently you are not setting the instance variables in the class. You are checking for negative balance and throwing the exception.
Also you need to improve the constructor in BankAccount class as follow:
public BankAccount(String name, double balance)throws NegativeAmountException {
if (balance < 0) {
throw new NegativeAmountException("Cannot create a BankAccount with a negative balance");
}
this.name = name;
this.balance = balance;
}
// Update the SavingsAccount class constructor as well
public SavingsAccount(String name, double balance, double interest) throws NegativeAmountException {
super(name, balance);
this.interest = interest; // this is missing in your code.
}
Other thing which I have observed it that, you are creating multiple instances of Scanner class. You can use the same keyboard instance every where in the main method. No need to create multiple instances. One of them is unnecessary.
Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Answer is already given, but there is also problem in your BankAccount class constructors, you did not assign instance variable to constructor arguments, you just check constraint so,
public BankAccount(String name, double balance)throws NegativeAmountException {
if (balance < 0)
throw new NegativeAmountException("Cannot create a BankAccount with a negative balance");
this.name = name;
this.balance = balance;
}
and
public BankAccount(String name) {
// set name and use 0 balance
this.name = name;
this.balance = 0;
}
thanks:)

Writing code - Class - Is this correct/Grade my code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Requirement:
Write a class, BankAccount, that has two instance variables for the name of the owner (of type String) and the balance (of type double). Add to this class the following methods:
A constructor that initializes the BankAccount instance variables to the values in two parameters, the name of the owner and the initial balance (>=0.0).
deposit: Given an amount (>0.0) to deposit, this method deposits it into the account.
withdraw: Given an amount (>0.0 and <= current balance) to withdraw, this method withdraws it from the account.
getName: This method returns the owner name.
getBalance: This method returns tth current balance. (Don't try to format a number-just take the default.)
Include appropriate checks in your methods to ensure that the amounts deposited and withdrawn satisfy the constraints specified. Use good encapsulation guidelines.
Did I interpret this correctly and execute it correctly and if not what needs fixed and how. Any help is appreciated.
Code:
import java.util.*;
public class BankAccount {
static Scanner in = new Scanner (System.in);
private static String name;
private static double balance;
public BankAccount(String n, double b){
System.out.println("Enter your name: ");
n = in.nextLine();
name = n;
System.out.println("Enter your current balance: ");
b = in.nextDouble();
balance = b;
}
public void deposit(){
System.out.println("Enter the amount you would like to deposit: ");
double deposit = in.nextDouble();
if(deposit > 0.0){
balance = balance + deposit;
}
}
public void withdraw(){
System.out.println("Enter the amount you would like to withdraw: ");
double withdraw = in.nextDouble();
if(withdraw > 0.0 && withdraw <= balance){
balance = balance - withdraw;
}
}
public static String getName(){
return name;
}
public static double getBalance(){
return balance;
}
}
A constructor that initializes the BankAccount instance variables to the values in two parameters, the name of the owner and the initial balance (>=0.0).
Well, you have the constructor, but you override the values passed to it...
public BankAccount(String n, double b){
System.out.println("Enter your name: ");
n = in.nextLine();
name = n;
System.out.println("Enter your current balance: ");
b = in.nextDouble();
balance = b;
}
Should simply be...
public BankAccount(String n, double b){
name = n;
balance = b;
}
deposit: Given an amount (>0.0) to deposit, this method deposits it into the account.
Your deposit method takes no parameters...
public void deposit(double amount){
if (amount > 0.0) {
balance = balance + deposit;
}
}
withdraw: Given an amount (>0.0 and <= current balance) to withdraw, this method withdraws it from the account.
Same as deposit, it takes no parameters...
public void withdraw(double amount){
if (amount > 0.0 && amount <= balance) {
balance = balance - amount;
}
}
getName: This method returns the owner name.
Check...
getBalance: This method returns tth current balance. (Don't try to format a number-just take the default.)
Check...
If it is the normal class for normal uses then this is ok.
But if it is being used in real time financial application then method should be synchornized for thread safe operation and also remove the static variable declaration because static variable belongs to class not to the instance.
Remove the static declarations. Unless you want each instance of BankAccount to refer to the same balance and name. Also your overloaded constructor doesn't need parameters if they aren't used/are set regardless of value.
public class BankAccount {
private Scanner in = new Scanner (System.in);
private String name;
private double balance;
public BankAccount(){
String n = "";
double b = 0.0;
System.out.println("Enter your name: ");
n = in.nextLine();
// check for null string
if(!n.equals("")) {
name = n;
}
System.out.println("Enter your current balance: ");
// ToDo: add a check for input
b = in.nextDouble();
balance = b;
}
...
public String getName(){
return name;
}
public double getBalance(){
return balance;
}
}
You could keep the overloaded constructor and use it in conjunction with the default constructor. Something like...
public BankAccount(){
String n = "";
double b = 0.0;
System.out.println("Enter your name: ");
// ToDo: add a check for input
n = in.nextLine();
System.out.println("Enter your current balance: ");
// ToDo: add a check for input
b = in.nextDouble();
this(n, b);
}
public BankAccount(String n, double b){
// ToDo: add checks for parameter integrity
this.name = n;
this.balance = b;
}

I cant get the java file to give me error

I created a main Java program that works like a bank giving a user their balance, withdrawls and transfer money.
import java.util.Scanner;
public class Lab12 {
public static void main(String[] args)
{
//Creating Two BankAccounts
BankAccount B1 = new BankAccount(1000, "ASU_ACCOUNT_110");
BankAccount B2 = new BankAccount(500, "ASU_ACCOUNT_100");
double amount;
Scanner scan = new Scanner(System.in);
//Account Deposit
System.out.println("Please Enter amount to deposit into ASU_ACCOUNT_110 Account");
amount = scan.nextDouble();
if(!B1.deposit(amount))
System.out.println("Error depositing amount in account. Please enter positive value.");
else
System.out.println("Successfully deposited $"+amount+". The current balance is "+B1.getBalance() );
//Account Withdrawal
System.out.println("Please Enter the amount you would like to withdraw from ASU_ACCOUNT_110");
amount = scan.nextDouble();
if(!B1.withdraw(amount))
System.out.println("Error withdrawing amount. You are either overdrawing or you have entered a negative value");
else
System.out.println("Successfully withdrew $"+amount+". The current balance is "+B1.getBalance());
//Account Transfer
System.out.println("Please Enter the amount you would like to transfer from ASU_ACCOUNT_110 to ASU_ACCOUNT_100");
amount = scan.nextDouble();
if(!B1.transfer(amount, B2))
{
System.out.println("Error transfering amount. You are either overdrawing or you have entered a negative value");
}
else
{
System.out.println("Successfully transferred $"+amount+".\nThe current balance in ASU_ACCOUNT_110 is "+B1.getBalance());
System.out.println("The current balance in ASU_ACCOUNT_100 is "+B2.getBalance());
}
//Account Display
System.out.println("\nThe details of the two accounts are:");
System.out.println("------------------------------------------");
display(B1);
System.out.println("------------------------------------------");
display(B2);
}
public static void display(BankAccount B)
{
System.out.println("The Account Number is "+B.getAccountNumber());
System.out.println("The balance is "+B.getBalance());
}
}
I created a second class that has methods and gets and calls the balances
public class BankAccount {
private String AccountNumber;
private double balance;
public BankAccount(double balance, String accountNumber)
{
this.balance = balance;
this.AccountNumber = accountNumber;
}
public boolean deposit(double amount)
{
return true;
}
public double getBalance()
{
return balance;
}
public boolean withdraw(double amount)
{
return true;
}
public boolean transfer(double amount, BankAccount b2)
{
return true;
}
public String getAccountNumber()
{
return AccountNumber;
}
}
The problem is that when I enter a negative amount for the deposit, withdrawal, transfer, I am not getting the error that I put in the main class
Any thoughts?
You do not check if the number is negative anywhere in BankAccount.deposit(double). You need to check if the code is negative like this:
public boolean deposit(double amount)
{
if(amount<0)
{
return false;
}else{
return true;
}
}
Your methods in BankAccount always return true. You can't expect them to sometimes signal failure unless you provide an implementation that does so.
For instance:
public boolean withdraw(double amount)
{
return true;
}
Will never signal failure because it always returns true. In order for your methods to behave the way you want them to, you must add more complex behavior. Something like:
public boolean withdraw(double amount)
{
//if the withdrawal is positive and does not exceed the balance
if (amount >= 0 && amount <= balance)
{
//remove money and signal success
balance -= amount;
return true;
}
//if either condition failed, signal failure
return false;
}
It looks like you simply forgot to implement these methods. Either that or you posses a fundamental misunderstanding of programming.
The deposit, withdraw and transfer methods always return true. Therefore you will never see the error message.

Categories