How do I add the deposit numbers? Do I need some kind of loop (I´m new to JAVA)?.
public class BankAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000, "Deposit 1");
account.deposit(2000, "Deposit 2");
System.out.println("Balance: " + account.getBalance());
account.deposit(3000, "Deposit 3");
account.deposit(4000, "Deposit 4");
System.out.println("Balance: " + account.getBalance());
}
private int currentBalance = 0;
private int getBalance() {
int finalBalance = depositAmount + currentBalance;
return finalBalance;
}
private int depositAmount;
public void deposit(int depositAmount) {
this.depositAmount = depositAmount;
}
}
Result should be:
Balance: 3000
Balance: 10000
Your deposit function is suspect. I think you want:
public void deposit(int depositAmount) {
this.currentBalance += depositAmount;
}
Note the +=: this will accumulate the deposit amount. You should also get rid of the class member depositAmount which is also causing bugs. Your getBalance function then reduces to
private/*ToDo - this will probably be public eventually*/ int getBalance() {
return currentBalance;
}
Two more issues though:
This function deposit is not called directly since you are calling a version that also takes a string. (I'm assuming that the function you give is called eventually though).
How will you model decimal values? Don't use a floating point as that will be imprecise. Use a currency type instead.
Well, this might work for you
public class BankAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.deposit(2000);
System.out.println("Balance: " + account.getBalance());
account.deposit(3000);
account.deposit(4000);
System.out.println("Balance: " + account.getBalance());
}
private int currentBalance = 0;
private int getBalance() {
return this.currentBalance;
}
public void deposit(int depositAmount) {
this.currentBalance = this.currentBalance + depositAmount;
}
}
You are actually adding everything to the same object account . hence you are getting the result of all values inside it .(i.e) sum of all inputs 10000
Related
I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.
If I try to print the output for one of the accounts I make I get a memory adress.
I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.
public class SavingsAccount {
// Class
int balance;
int amountToDeposit;
int amountToWithdraw;
//Constructor
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
amountToDeposit = deposit;
amountToWithdraw = withdraw;
}
//Functions thats I wanna call
// Setting balance
public void checkBalance() {
System.out.println("Hello!");
System.out.println("Your balance is " + balance);
}
// Depositing amounts
public void deposit(int amountToDeposit) {
balance = balance + amountToDeposit;
System.out.println("You just deposited" + amountToDeposit);
}
// Withdrawing amounts
public int withdraw(int amountToWithdraw) {
balance = balance - amountToWithdraw;
System.out.println("You just withdrew" + amountToWithdraw);
return amountToWithdraw;
}
// Main
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
//Check balance
System.out.println(test); // Will give a memory adress
}
}
I would like to use my functions on the object I make and print the result.
Thanks for reading.
Hello you can implement toString to print the object as below:
package com.stuart.livealert;
public class SavingsAccount {
// Class
int balance;
int amountToDeposit;
int amountToWithdraw;
//Constructor
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
amountToDeposit = deposit;
amountToWithdraw = withdraw;
}
//Functions thats I wanna call
// Setting balance
public void checkBalance() {
System.out.println("Hello!");
System.out.println("Your balance is " + balance);
}
// Depositing amounts
public void deposit(int amountToDeposit) {
balance = balance + amountToDeposit;
System.out.println("You just deposited" + amountToDeposit);
}
// Withdrawing amounts
public int withdraw(int amountToWithdraw) {
balance = balance - amountToWithdraw;
System.out.println("You just withdrew" + amountToWithdraw);
return amountToWithdraw;
}
#Override
public String toString() {
return "{balance : " + balance + " deposit : " + amountToDeposit + " withdraw : " + amountToWithdraw + " }";
}
// Main
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
//Check balance
System.out.println(test); // Will give {balance : 5000 deposit : 200 withdraw : 100 }
}
}
You can call your functions in the constructor:
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
deposit(deposit);
withdraw(withdraw);
checkBalance();
}
Then you will see all the System.out messages without the need to change the main method.
I have the feeling that I have done something wrong and I don't quite
understand how to call my functions on the object.
You can call your methods with the variable name of a SavingsAccount, followed by a ".", and then the method you would like to call.
So, rather than
//Check balance
System.out.println(test); // Will give a memory address
You can do this, for example:
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
test.checkBalance();
}
or
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
test.deposit(50);
test.checkBalance();
}
With that in mind, perhaps it makes more sense to only specify a starting balance when constructing a SavingsAccount. Hope this helps!
This will be my second question on here; I try not to ask because I don't fancy receiving help for my homework. But I'm just plain stuck.
I'm currently writing a program that stores and updates information for some example bank accounts. My issue is that, somehow, my output has two decimal points.
Example:
"2000.02008.3333333333333"
Side notes: I'm in a Tier II java course, so yes, my code isn't the prettiest. Also, please only offer hints as to where I should make changes. As I said earlier, I try really hard not to ask for help and I don't want my request for help to be misconstrued as cheating. Finally, I do know about syso formatting and will be doing that with the Title information in my driver. The way I did it in there was just faster for me at the time while I fleshed out the rest of the details.
Many thanks in advance to any help provided!
Here's my current code:
public class SavingsAccount
{
private static double annualInterestRate;
private final int ACCOUNT_NUMBER;
private double balance;
public SavingsAccount(int ACCOUNT_NUMBER, double balance)
{
this.ACCOUNT_NUMBER = ACCOUNT_NUMBER;
this.balance = balance;
}
public static double setAnnualInterestRate(double aIR)
{
annualInterestRate = aIR;
return annualInterestRate;
}
public int getAccountNumber()
{
return ACCOUNT_NUMBER;
}
public double getBalance()
{
return balance;
}
public double addMonthlyInterest()
{
balance += (balance * annualInterestRate / 12);
return balance;
}
}
DRIVER
public class Chapter13
{
public static void main(String[] args)
{
double annualInterestRate = .05;
SavingsAccount saver1 = new SavingsAccount(10002, 2000);
SavingsAccount saver2 = new SavingsAccount(10003, 3000);
SavingsAccount.setAnnualInterestRate(annualInterestRate);
System.out.println("Month Acount# Balance Account# Balance");
for(int i = 0; i < 13; i++)
{
System.out.println(i + " " + saver1.getBalance() +
saver1.addMonthlyInterest());
}
}
}
That's because the balance and annualInterestRate are getting printed without any space between them. Add a tab or space between them so that they are printed separately.
System.out.println(i + " " + saver1.getBalance() + "\t" // tab
saver1.addMonthlyInterest());
System.out.println(i + " " + saver1.getBalance() + " " // space
saver1.addMonthlyInterest());
so I'm having an issue writing my code such that i will be able to create an equals method that will return true if 2 credit cards are equal if they have the same Security code, company and account number.
Heres my code so far.
public class CreditCard {
private double balance;
public static double interestRate;
public static String personname;
public static String company;
public static double creditLine;
public CreditCard ()
{
balance = 0;
}
public static void setIntRate (double rate)
{
interestRate = rate;
System.out.println("The Interest rate for this card is : " + interestRate);
}
public static double getIntRate ()
{
return interestRate;
}
public static void setPersonName (CreditCard card ,String pName)
{
personname = pName;
System.out.println("Name on card: " + personname);
}
public static void setCompany (CreditCard card, String compName)
{
company =compName;
System.out.println("The Company name is : "+ company);
}
//creates new card number
public static void CardNum (CreditCard card)
{
int[] accountnumber = new int [16];
Random generator = new Random ();
for (int i =0; i<16; i++)
accountnumber [i] = (int)(Math.random()*10);
System.out.println ("The Account number for this card is: " + (java.util.Arrays.toString(accountnumber))+"");
}
//Creates new securitycode
public static void getSecurityCode (CreditCard card)
{
int[] securitycode = new int [3];
Random generator = new Random ();
for (int i =0; i<3; i++)
securitycode [i] = (int)(Math.random()*10);
System.out.println ("The security code for this card is: " + (java.util.Arrays.toString(securitycode))+"");
}
public static void setexpirationdate(int MM, int YY)
{
System.out.println("The expiration date for this card is: " + MM + "/"+ YY + "\n");
}
public static void setCreditLine (int cLine){
creditLine =cLine;
}
public static void getCreditLine (CreditCard card)
{
System.out.println( " CreditLine is : $" + creditLine);
}
// buys something
public void buyWithCreditCard (double amount)
{
balance = balance + amount;
}
//Inserts money to reduce balance
public double paybalance (double amount)
{
if (balance >= amount){
balance = balance - amount;
roundBalance();}
else{
creditLine = creditLine + (amount - balance);
balance = 0;
System.out.println("Your new CreditLine is: "+creditLine);
roundBalance();
}
return amount;
}
// adds interest to balance
public void addInterest ()
{
double interest = balance * getIntRate ();
balance = balance + interest;
roundBalance ();
}
private void roundBalance ()
{
balance = (double)(Math.round(balance*100))/100;
}
public double checkBalance (){
return balance;
}
//Shows Credit Card Debt
public static void showBalance (CreditCard card)
{
System.out.print(card.balance);
}
}
and then the class that utilizes the CreditCard Class.
public class CreditCardDemo {
public static void main (String [] args)
{
//Creates cards 1 and 2
CreditCard firstCard = new CreditCard ();
CreditCard secondCard = new CreditCard ();
//Calls for card info 1
System.out.println("First card Information is:");
CreditCard.setPersonName(firstCard,"John White");
//CreditCard.getName(firstCard);
CreditCard.setCreditLine(600);
CreditCard.getCreditLine(firstCard);
CreditCard.setCompany(firstCard,"Visa");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(firstCard);
CreditCard.getSecurityCode(firstCard);
CreditCard.setexpirationdate(11, 17);
//call for card info 2
System.out.println("Second card Information is:");
CreditCard.setPersonName(secondCard,"Jack Black");
CreditCard.setCreditLine(2600);
CreditCard.getCreditLine(secondCard);
//CreditCard.getName(secondCard);
CreditCard.setCompany(secondCard,"Discover");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(secondCard);
CreditCard.getSecurityCode(secondCard);
CreditCard.setexpirationdate(10, 19);
//Purchases
System.out.println("\nYou bought something for $5.00");
firstCard.buyWithCreditCard (5.00);
System.out.println("You bought another item for $12.00");
firstCard.buyWithCreditCard(12.00);
System.out.println("You bought another item for $15.00");
firstCard.buyWithCreditCard(15.00);
System.out.println("You bought another item for $33.42");
firstCard.buyWithCreditCard(33.42);
//Display Current Balance
System.out.print("You currently owe: $");
CreditCard.showBalance(firstCard);
//Interest Adds onto it
if (firstCard.checkBalance () > 50.00){
System.out.println("\nInterest has been added");
firstCard.addInterest ();
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
System.out.println("");
//Payment
System.out.println("You have overpaid your balance.");
firstCard.paybalance (70);
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
}
}
}
So if anyone could show me how to create a method in the CreditCard class that would allow me to check if the firstCard and secondCard, that would be great. Thanks a bunch :)
If you use NetBeans, you can simply auto-generate the equals function (not sure about Eclipse). Other than that it boils down to overwriting the equals function of Object.
Make sure to check that both are of the same class and make sure to check for null. Java recommends to as well overwrite the hashCode function, however that depends on your use-case.
first of all, i'm not that advanced in java, but this seems simple enough still.
The problem here seems that the security code is never saved (the method getSecurityCode is void and all variables are only local)
Same goes for the company
nonetheless, here's an example, assuming you fixed that and made a method getCode that returns the code (as int) and a method getAccountNumber, that returns that number (as int). (and assuming it's no problem to make those methods public)
public boolean equals(CreditCard creditCard1, CreditCard creditCard2){
if (creditCard1 == null || creditCard2 == null)
return creditCard1 == creditCard2;
boolean equalCode = (creditCard1.getCode() == creditCard2.getCode());
boolean equalCompany = creditCard1.company.equals(creditCard2.company);
boolean equalAccountNumber = (creditCard1.getAccountNumber() == creditCard2.getAccountNumber());
return equalCode && equalCompany && equalAccountNumber;
}
It would be good practice to make the variables private and make some getters, but that's up to you.
I am having some issues with the following syntax.
I am currently learning Java and have been going through a past exam paper to help build my knowledge of Java.
Here is the question:
Write a class Account that has instance variables for the account number and current balance of the account. Implement a constructor and methods getAccountNumber(), getBalance(), debit(double amount) and credit(double amount). In your implementations of debit and credit, check that the specified amount is positive and that an overdraft would not be caused in the debit method. Return false in these cases. Otherwise, update the balance.
I have attempted to do this HOWEVER, I have not implemented the boolean functions for debit and credit methods. I just wanted to build the program first and attempt to get it working. I was going to look at this after as I was not sure how to return true or false whilst also trying to return an amount from the said methods.
Please forgive any errors in my code as I am still learning Java.
I can run my code, but when I enter deposit it does not seem to work correctly and I would appreciate any pointers here please.
Here is my code:
import java.util.*;
public class Account {
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput == withdraw)
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput == deposit)
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}
Again please forgive any errors in my code. I am still learning its syntax.
In the if-statement if(userInput == withdraw) you are attempting to compare String objects.
In Java to compare String objects the equals method is used instead of the comparison operator ==
if(userInput.equals(withdraw))
There are several instances in the code that compares String objects using == change these to use equals.
Also when using conditional blocks it is best to surround the block with braces {}
if(true){
}
You don't use brackets so only the first line after your if-statement gets executed. Also, String's should be compared using .equals(otherString). Like this:
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: "); //Only executed if userInput == withdraw
amount = in.nextDouble(); //Always executed
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
//All executed
}
Do this:
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
if (userInput.equals(deposit)) {
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
Note that if your amount to withdraw exceeds your current balance, you will get a 'warning message' but your withdrawal will continue. Thus you'll end up with a negative sum of money. If you don't want to do this, you have to change it accordingly. But, this way it shows how the use of brackets (or not using them) has different effects.
if (userInput == deposit)
should be
if (userInput.equals(deposit))
Same for withdrawal.
On these methods:
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
The inputs to the functions really shouldn't include the current balance, the object already knows what the current balance is (its being held in the objects currentBalance field, which as has been pointed out shouldn't be static).
Imagine a real cash machine that behaved like this:
Whats my current balance:
£100
CreditAccount("I promise my current balance is £1 Million, it really is", £10):
Balance:£1,000,010
Edit: Include code to behave like this
import java.util.*;
public class Account {
private int accountNumber;
private double currentBalance; //balance kept track of internally
// ***** CONSTRUCTOR *****//
public Account(int accountNumber, double currentBalance) {
this.accountNumber = accountNumber;
this.currentBalance = currentBalance;
}
public int getAccountNumber() {
return accountNumber;
}
public double getcurrentBalance() {
return currentBalance;
}
public boolean debit(double amount) {
//we just refer to the objects fields and they are changed
if (currentBalance<amount){
return false; //transaction rejected
}else{
currentBalance -= amount;
return true;
//transaction approaved and occured
}
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public void credit( double amount) {
//credits will always go through, no need for return boolean
currentBalance += amount;
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public static void main(String [] args){
Account acc=new Account(1234,1000);
acc.credit(100);
System.out.println("Current ballance is " + acc.getcurrentBalance());
boolean success=acc.debit(900); //there is enough funds, will succeed
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
success=acc.debit(900); //will fail as not enough funds
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
}
}
I've not bothered using the typed input because you seem to have the hang of that
Without '{' and '}' the first line after an if statement only gets executed as part of that statement. Also, your if (userInput == deposit) block isn't correctly indented, it shouldn't be under the if (userInput == withdraw). And string comparisons should be done using userInput.equals(withdraw)
For the debit and credit methods:
public static boolean debit(double currentBalance, double amount) {
currentBalance -= amount;
if<currentBalance < 0){
return false
}
return true;
}
public static boolean credit(double currentBalance, double amount) {
currentBalance += amount;
if<currentBalance > 0){
return false
}
return true;
}
Now I think I have the boolean values mixed up. The description is a little bit unclear on what to return for each method.
Use equals() method instead == which compares the equality of Objetcs rather values
import java.util.*;
public class Account{
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput .equals(deposit))
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}
For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.