I cant get the java file to give me error - java

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.

Related

Java: ArrayList item not returning when searched for

I am trying to outline an ArrayList of bank accounts in my main method, call a search on all accounts in that list, if the account is there...deposit money. Actual specs of program:
Design and implement a program that performs in the following way:
• When the program starts, two bank accounts are created, using names and
numbers which are written into the code;
• The user is then asked to enter an account number, followed by an amount to
deposit in that account;
• The balance of the appropriate account is then updated accordingly—or if an
incorrect account number was entered a message to this effect is displayed; this search portion of the spec is whats throwing me.
• The user is then asked if he or she wishes to make more deposits;
• If the user answers does wish to make more deposits, the process continues;
• If the user does not wish to make more deposits, then details of both accounts
(account number, account name and balance) are displayed.
When i run the code it returns output for when the account is not found... clearly the accounts I am defining arent being transferred to the ArrayList as im expecting.
BankAccount class:
import java.util.ArrayList;
public class BankAccount {
// the attributes
private String accountNumber;
private String accountName;
private double balance;
private char choice;
//Notice the static attribute
private static double interestRate;
// the methods
// the constructor
public BankAccount(String numberIn, String nameIn)
{
accountNumber = numberIn;
accountName = nameIn;
balance = 0;
}
// methods to read the attributes
public String getAccountName()
{
return accountName;
}
public String getAccountNumber()
{
return accountNumber;
}
public double getBalance()
{
return balance;
}
// methods to deposit and withdraw money
public void deposit(double amountIn)
{
balance = balance + amountIn;
}
public void withdraw(double amountIn)
{
if (amountIn > balance)
{
System.out.println("Sorry, there is an insufficient amount in your account to complete this withdrawal");
}
else
{
System.out.println("Withdrawal Successful");
balance = balance - amountIn;
}
}
public void setInterestRate(double rateIn)
{
interestRate = rateIn;
}
public double getInterestRate()
{
return interestRate;
}
public void addInterest()
{
balance = balance + (balance *interestRate)/100;
}
}
Bank Class:
import java.util.ArrayList;
public class Bank {
ArrayList<BankAccount> list = new ArrayList<>();
// helper method to find the index of a specified account
private int search(String accountNumberIn)
{
for(int i = 0; i <= list.size() - 1; i++)
{
BankAccount tempAccount = list.get(i); // find the account at index i
String tempNumber = tempAccount.getAccountNumber(); // get account number
if(tempNumber.equals(accountNumberIn)) // if this is the account we are looking for
{
return i; // return the index
}
}
return -999;
}
// return the total number of items
public int getTotal()
{
return list.size();
}
// return an account with a particular account number
public BankAccount getItem(String accountNumberIn)
{
int index = search(accountNumberIn);
if(index != -999) // check that account exists
{
return list.get(index);
}
else
{
return null; // no such account
}
}
// add an item to the list
public boolean addAccount(String accountNumberIn, String nameIn)
{
if(search(accountNumberIn) == -999) // check that account does not already exist
{
list.add(new BankAccount(accountNumberIn, nameIn)); // add new account
return true;
}
return false;
}
// deposit money in a specified account
public boolean depositMoney(String accountNumberIn, double amountIn)
{
BankAccount acc = getItem(accountNumberIn);
if(acc != null)
{
acc.deposit(amountIn);
return true; // indicate success
}
else
{
return false; // indicate failure
}
}
// withdraw money from a specified account
public boolean withdrawMoney(String accountNumberIn, double amountIn)
{
BankAccount acc = getItem(accountNumberIn);
if(acc != null && acc.getBalance() >= amountIn)
{
acc.withdraw(amountIn);
return true; // indicate success
}
else
{
return false; // indicate failure
}
}
// remove an account
public boolean removeAccount(String accountNumberIn)
{
int index = search(accountNumberIn); // find index of account
if(index != -999) // if account exists account
{
list.remove(index);
return true; // remove was successful
}
else
{
return false; // remove was unsuccessful
}
}
}
And finally the testing class with main method:
import java.util.ArrayList;
public class BankAccountTester {
public static void main(String args[])
{
Bank myBank = new Bank();
ArrayList<BankAccount> accountList = new ArrayList<>();
accountList.add(new BankAccount("123","Susan Richards"));
accountList.add(new BankAccount("44567109","Delroy Jacobs"));
accountList.add(new BankAccount("46376205","Sumana Khan"));
char choice;
do {
System.out.println("Please enter your account number:");
String myAcc = EasyScanner.nextString();
BankAccount account = myBank.getItem(myAcc);
System.out.println("Please enter an amount to deposit: ");
double depIn = EasyScanner.nextDouble();
boolean found = myBank.depositMoney(myAcc, depIn);
if (found)
{
System.out.println("Deposit made");
} else
{
System.out.println("Invalid account number"); //this is running everytime
}
System.out.println("Would you like to deposit again? (y/n)");
choice = EasyScanner.nextChar();
} while (choice == 'y' || choice == 'Y');
System.out.println("Account Details..... \n");
for(BankAccount item : accountList)
{
System.out.println("Account number: " + item.getAccountNumber());
System.out.println("Account name: " + item.getAccountName());
System.out.println("Current balance: " + item.getBalance());
System.out.println();
}
}
}
The output i get is as follows:
Please enter your account number:
123
Please enter an amount to deposit:
10
**Invalid account number**
Would you like to deposit again? (y/n)
I cant figure out why the account number isnt being picked up, although I can guess that the ArrayList being searched doesnt hold the account information that has been input.
Any help would be appreciated!
You have to add to accountList in myBank not in main.
myBank.addAccount ("123","Susan Richards"));
myBank.addAccount ("44567109","Delroy Jacobs"));
myBank.addAccount ("46376205","Sumana Khan"));

How to print balance in a banking program (Java) [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 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.

How can I allow a user to create different types of objects, in order to use Java polymorphism?

I am currently taking lessons in OOP java. In my code below i am implementing polymorphism at run time as well as inheritance. I am creating a constant named "balance".
The goal of this program is to create a class called Account and extend the class with two types of classes called SBaccount and current.
The common attributes shared with Account is name, number and amount. So far i have a working code but its not quite doing what I want yet.
I want to be able to ask the user for the type of account that needs to be created, once the user specifies the type I want to validate the user input. I also want for example if a user deposits xx amount, that amount should be added to the balance and then stored. I want in the "withdraw" method, when the user makes a withdrawal it should be taken from the balance.
My code:
import java.util.Scanner;
abstract class Account{
String number;
String name;
int amount;
static final int balance = 1000;
int bal;
public Account(){
}
int deposit(int i) {
return i;
}
void withdrawal(int i){
}
}
final class sbaccount extends Account {
public sbaccount() {
// TODO Auto-generated constructor stub
}
int deposit (int money){
bal = money + balance;
System.out.println("You have deposited :$"+money );
System.out.println("Your Account balance is now :"+bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
final class current extends Account {
public current() {
}
int deposit ( int money){
bal = money + balance;
System.out.println("You have deposited :$"+money);
System.out.println("Your Account balance is now :"+ bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
public class oopassignment {
public static void main(String[] args) {
String type;
Scanner input = new Scanner (System.in);
System.out.println("What type of account do you want to create? :");
type=input.nextLine();
Account sb;
sb = new sbaccount();
sb.deposit(500);
sb.withdrawal(100);
sb = new current();
sb.deposit(500000);
sb.withdrawal(1000000);
}
}
So you can do the following task through class.newInstance() method.
System.out.println("What type of account do you want to create? :");
String account_type = input.next();
Class c = Class.forName(account_type);
Account sb = (Account)c.getDeclaredConstructor().newInstance();
The class c will load the class according to the argument passed. And object will be created through casting (required as initially the the object is of type "Class").
So finally your code will be (some modification is done) :
import java.util.Scanner;
abstract class Account {
String number;
String name;
int amount;
static final int balance = 1000;
int bal;
abstract int deposit(int i);
abstract void withdrawal(int i);
}
final class sbaccount extends Account {
int deposit(int money) {
bal = money + balance;
System.out.println("You have deposited :$" + money);
System.out.println("Your Account balance is now :" + bal);
return bal;
}
void withdrawal(int withdraw) {
if (bal <= balance) {
System.out.println("Your balance is too low for withdrawal!");
} else {
amount = bal - withdraw;
System.out.println("You have withdrawn :$" + withdraw);
System.out.println("Your Account balance is now :" + amount);
}
}
}
final class current extends Account {
int deposit(int money) {
bal = money + balance;
System.out.println("You have deposited :$" + money);
System.out.println("Your Account balance is now :" + bal);
return bal;
}
void withdrawal(int withdraw) {
if (bal <= balance) {
System.out.println("Your balance is too low for withdrawal!");
} else {
amount = bal - withdraw;
System.out.println("You have withdrawn :$" + withdraw);
System.out.println("Your Account balance is now :" + amount);
}
}
}
public class oopassignment {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("What type of account do you want to create? :");
String account_type = input.next();
// The only valid optios are : sbaccount & current.
// If any other class name is inputted. It will show exception
Class c = Class.forName(account_type);
Account sb = (Account)c.getDeclaredConstructor().newInstance();
sb.deposit(500);
sb.withdrawal(100);
sb = new current();
sb.deposit(500000);
sb.withdrawal(1000000);
}
}
Let me know if any modification is needed to answer.

Java: Returning user input

Having an issue receiving the "Just Tax." Program compiles, will not calculate sales tax on output - simply returns a "0." The "Sale" method (not within listed code) will acknowledge and print the amount of the sale, however. Not sure what I'm doing incorrectly. Thanks!
//...
Purchase saleAmount = new Purchase();
//...
System.out.println("Please enter a positive (+) number for the sale amount: $");
double saleAmt = input.nextDouble();
saleAmount.setSale(saleAmt);
//...
System.out.println("The 5% tax applied is: " + saleAmount.getJustTax());
public class Purchase
//all data types have been declared
final double SALES_TAX = 0.05;
{
//Initial Sale Cost
public double getSale()
{
return sale;
}
public void setSale(double amount)
{
amount = sale;
}
//Get Just Sales Tax
public double getJustTax()
{
return justTax;
}
public void setJustTax(double sale)
{
justTax = (sale * SALES_TAX);
}
}
The assignment in your setSale method is backwards. Currently, it assigns whatever is in sale to your local variable amount.
Change
public void setSale(double amount)
{
amount = sale;
}
to
public void setSale(double amount)
{
sale = amount;
}
public void setSale(double amount)
{
amount = sale;
}
This is causing the issue. What you're currently doing is taking the method argument and assigning your sale variable to it. (I cannot see it in the code however).
public void setJustTax(double sale)
{
justTax = (sale * SALES_TAX);
}
This means when the above code is called, sale still has no value to it and I'll guess that sale is instantiated with 0.

Java program doesn't add amounts correctly [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So I am still fairly new to java. I have written this but am not sure as to why when I run it, the amounts will not add to what is set in the client.
For example: I enter 500 as starting balance, if I hit deposit, and type 500, and then hit case 3, it should say 1000 but it still says 500. And then If i hit withdraw, it says I have -500.
Any ideas? Thanks
package bankaccount;
import java.util.Random;
import java.util.Scanner;
public class Client {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String cusName = input.nextLine();
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount b1 = new BankAccount(cusName, accNo, balance);
int menu;
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
Money.amount = input.nextInt();
b1.getDeposit();
break;
case 2:
System.out.println("Current Account Balance=" + b1.getBalance());
System.out.print("Enter withdrawal amount:");
Money.amount = input.nextInt();
b1.getWithdraw();
break;
case 3:
b1.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
public class Money
{
public static int accountNumber, balance=0;
static int amount;
static String name;
public void setDeposit(int amount) {
balance = balance + amount;
}
public int getDeposit()
{
balance = balance + amount;
if (amount < 0) {
System.out.println("Invalid");
}
return 1;
}
public void setBalance(int b)
{
b = balance;
}
public int getBalance()
{
return balance;
}
public void setWithdraw(int amount) {
balance = balance - amount;
}
public int getWithdraw()
{
balance = balance - amount;
if (balance < amount)
{
System.out.println("Not enough funds.");
return 1;
}
else if (amount < 0) {
System.out.println("Invalid");
return 1;}
else
return 0;
}
import java.util.*;
public class BankAccount extends Money {
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
this.customerMoney = new Money();
}
void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
void displayBalance() {
System.out.println("Balance:" + balance);
}
public Money getMoney(){
return this.customerMoney;
}
}
The biggest problem is at statement balance=0
public static int accountNumber, balance=0;
^^^^^^^^^
Every time when you are going to insert amount, your balance is ZERO.
You should have used setDeposit(input.nextInt())
In public void setBalance(int b), b = balance; should have been balance = b;
Also, your amount, balance variables should be Float instead of int as balance/amount can be 23434.22.
I would remove all the public static int variables that you are using. These are going to cause confusion because it's much harder to follow what their values are as the program executes. Best to encapsulate your logic into BankAccount using private variables and public methods to modify them.
I would, personally, eliminate the Money class from your code. It's just going to cause confusion and with your simplified logic is not required. Let's assume the account holds some arbitrary count of 'money' but there is no real-life money actually backing it up - (kind of like real life, it's just 'numbers on a screen' right?) - in this case we wouldn't need the Money class, just an int for our BankAccount's balance.
Without trying to make too many changes to your underlying functionality, I rewrote as the below two classes:
A BankAccount class:
package banking;
public class BankAccount {
/**
* The balance of this account. <br/>
* Assumes integer money (Floating point math is horrible and who really
* needs pesky pence or cents right?!)
*/
private int balance;
/**
* The account number
*/
private final int acctNum;
/**
* Name of the account holder
*/
private final String name;
/**
* Construct our basic account with an account number, account holder and
* starting balance.
*
* #param name
* #param accNo
* #param bal
*/
public BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
}
/**
* Make a deposit to this account by adding a fixed sum to the existing
* balance. <br/>
*
* #param amount
*/
public void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("You cannot deposit zero or less");
} else {
this.balance += amount;
}
}
/**
* Make a withdrawal from this account by subtracting a fixed amount from
* the existing balance. <br/>
*
* #param amount
*/
public void withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("Insufficient Funds");
} else if (amount <= 0) {
throw new IllegalArgumentException("You cannot withdraw zero or less");
} else {
balance -= amount;
}
}
/**
* Get the account holder name.
*
* #return
*/
public String getName() {
return name;
}
/**
* Get the current account balance.
*
* #return
*/
public int getBalance() {
return balance;
}
/**
* Get the account identifier for this account.
*
* #return
*/
public int getAcctNum() {
return acctNum;
}
/**
* Debug print method.
*/
public void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
}
And the main class:
package banking;
import java.util.Random;
import java.util.Scanner;
public class BankMain {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String customerName = input.nextLine();
Random randomGenerator = new Random();
int acctNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount acct = new BankAccount(customerName, acctNo, balance);
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
int menu;
do {
final int transaction;
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
transaction = input.nextInt();
acct.deposit(transaction);
break;
case 2:
System.out.println("Current Account Balance=" + acct.getBalance());
System.out.print("Enter withdrawal amount:");
transaction = input.nextInt();
try {
acct.withdraw(transaction);
} catch (IllegalArgumentException iaEx) {
System.out.println(iaEx.getMessage());
}
break;
case 3:
acct.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
}
This is still far from perfect, but I feel it's easier to follow for having the static variables and Money class removed.
You have many problems with the code e.g. none of your fields should be static, but the main one is that you have multiple duplicated fields.
e.g. In Money you have
public static int accountNumber, balance=0;
static int amount;
static String name;
and in BankAccount you have
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
which means you have multiple fields called name, balance and amount. Some of the code uses the first group of fields and some of the code uses the second. You also have a customerMoney which is not updated directly.
To avoid confusion I suggest you have each field be non-static and in only one place. Remove the customerMoney as you might be tempted to use it ;)

Categories