public class AccountDriver {
public static void main(String[] args) {
// ID, Balance, Annual Interest Rate
Account number1 = new Account();
Account number2 = new Account(1122, 20000.00, 0.045);
// Default account
System.out.println("The Account ID is: " + number1.getId());
System.out.println("The Account Balance is: " + number1.getBalance());
// System.out.println("The Account Balance is: "+
// number1.getMontlyInterest());
System.out.println("");
// Ask to withdraw 2500
System.out.println("The Account ID is: " + number2.getId());
number2.withdraw(2500.00);
number2.deposit(3000.00);
System.out.println("Account Balance is " + number2.getBalance());
// System.out.println("The montly interest is : "+
// number2.getMontlyInterest());
System.out.println("");
}
}
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public Account(int id, double balance, double annualInterestRate) {
this.setId(id);
this.setBalance(this.balance);
this.setBalance(annualInterestRate);
}
public Account() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMontlyInterest(double montlyInterest) {
// Given Formula
// double MontlyInterest= this.balance * get.MontlyInterestRate();
return montlyInterest;
}
public double getMontlyInterestRate(double montlyInterestRate) {
// Given Formula
montlyInterestRate = this.annualInterestRate / 12;
return montlyInterestRate;
}
double withdraw(double amount) {
return balance -= amount;
}
double deposit(double amount) {
return balance += amount;
}
}
I am getting error
The Account ID is: 0
The Account Balance is: 0.0
The Account ID is: 1122
Account Balance is 20500.0
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getMontlyInterestRate(double) in the type Account is not applicable for the arguments ()
at Account.getMontlyInterest(Account.java:41)
at AccountDriver.main(AccountDriver.java:21)
You did 2 small mistakes in your code.
In your constructor these 2 lines
this.setBalance(this.balance); // this.balance is the instance variable and not the parameter passed
^^^^ - this is not required, just use the balance parameter passed.
this.setBalance(annualInterestRate); // you are re-writing the balance with interest rate
^^^^^^^^^^ - You need to set annual interest rate and not the balance here.
should be
this.setBalance(balance); // sets the balance passed to the instance variable balance
this.setAnnualInterestRate(annualInterestRate); // sets the annual interest rate
Now since the annualInterestRate is set, you can get the monthly interest rate by modifying getMontlyInterestRate method like this.
public double getMontlyInterestRate() {
// Given Formula
return this.annualInterestRate / 12;
}
And you can print your monthly interest rate by uncommenting your System.out.println code.
System.out.println("The montly interest is : "+ number2.getMontlyInterestRate());
And the monthly interest method would look like this:
public double getMontlyInterest() { // no parameter required
// Given Formula
double MontlyInterest = this.balance * getMontlyInterestRate(); // balance multiplied by monthly interest rate
return MontlyInterest; // return the value
}
System.out.println("The montly interest is : "+ number2.getMontlyInterest());
Related
I am trying to call a getName and getBalance method from another class called Account in my printbalances method in class bank. but it is not working it prints null after inputing customer and balance. can someone explain why and how to fix it? I can honestly say I don't know why it is not working.
Here is the class that is calling it:
class Bank {
ArrayList<Account> accounts = new ArrayList<>();
Scanner input = new Scanner(System.in);
Scanner q;
String name;
double balance;
private Account account = new Account(name, balance);
public void enterCustomers() {
System.out.println("Enter customer names or press q to quit entering names: ");
while (true) {
String name;
double balance;
System.out.print("Enter a customer name: ");
name = input.next();
if ("q".equals(name)) { //tried using == to break but wouldnt work so tried .equals since comparing strings and works
break;
}
System.out.print("Enter the opening balance : ");
balance = input.nextDouble();
accounts.add(new Account(name, balance));
}
}
public void printBalances() {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
System.out.println(account.getName() + account.getBalance());
}
and here is the classs where the get methods are stored:
class Account {
private String name;
private double balance;
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
//public void setName(String name) {
// this.name = name;
//}
public double getBalance() {
return balance;
}
//public void setBalance(double balance) {
// this.balance = balance;
//}
public void deposit(double amount) {
balance += amount;
}
public void withdrawal(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println(" Insufficient Balance. ");
}
}
}
The output it gives me is this:
Enter customer names or press q to quit entering names:
Enter a customer name: john
Enter the opening balance : 200
Enter a customer name: mike
Enter the opening balance : 2
Enter a customer name: q
==========================
Opening account balance
==========================
Customer Balance
==========================
null0.0
(1)deposit (2)withdraw (0)quit
I dont know why null 0.0 appears and can someone explain why?
Right now you are initializing account like this:
private Account account = new Account(name, balance);
But here name and balance are not initialized, so they are null and zero respectively by default. It looks more like you want to print the name and balance of a specific Account object, so I would pass it as an argument to printBalances:
public void printBalances(Account account) {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
System.out.println(account.getName() + " : " + account.getBalance());
}
Or if you wanted to print every balance in the accounts ArrayList:
public void printBalances() {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
for(Account account : accounts) {
System.out.println(account.getName() + " : " + account.getBalance());
}
}
Are there any more references to account?
You are likely overriding it at some point because it has a name of null and a balance of 0.0
I would like someones expert opinion on both of my account class and the test account interest class. The issue I am facing is that the code from the test account interest class just multiplies on from the previous 12 month compute interest when it is supposed to be used only once.
The issue is in the
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
It is in this method of where the problem is that I should not use the balance but to use a variable that will store the answer but I did not understand the person that very clearly and he was very vague by only stating a variable should be used.
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
This is my test account interest class:
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(100, 0.1);//0.10);
Account acc2 = new Account(133, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
//acc1.deposit(100);
//acc1.withdraw(100);
System.out.println(acc1.computeInterest(12));
// //acc1.computeInterest(12);
// System.out.println(acc1.computeInterest(24));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(100);
acc2.deposit(100);
//acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
This is the final output:
110.00000000000001
191.51999999999998
As you can see for the second one the figure is multiplied by the 12 month compute interest with the 24 month compute interest this stems from the method in the account class:
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
If I take out the balance it still causes and error so I confused on this particular part.
Code,
public double computeInterest(int n) {
balance = balance * (Math.pow((1 + rate), n / 12));
return balance;
}
should be changed to
public double computeInterest(int n) {
return balance * Math.pow(1 + rate, n / 12);
}
You shouldn't change balance field while computing interest. You might like to have a separate method to update balance where you do , balance = balance + computed_interest or something like that.
Also, I have remove unnecessary parenthesis. That was not an error but simply making your code less readable.
Here my code.
Main SavingsDemo.java
public class SavingsDemo
{
public static void main(String[] args)
{
// Create a SavingsAccount object with a $100 balance,
// 3% interest rate, and a monthly service charge
// of $2.50.
SavingsAccount savings =
new SavingsAccount(100.0, 0.03, 2.50);
// Display what we've got.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Make some deposits.
savings.deposit(25.00);
savings.deposit(10.00);
savings.deposit(35.00);
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Make some withdrawals.
savings.withdraw(100.00);
savings.withdraw(50.00);
savings.withdraw(10.00);
savings.withdraw(1.00);
savings.withdraw(1.00);
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Do the monthly processing.
savings.monthlyProcess();
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
}
}
Superclass BankAccount.java
public class BankAccount
{
private double balance; //The balance in the account
private int numDeposits; //Number of deposits this month
private int numWithdrawals; //Number of withdrawals
private double interestRate; //Annual interest rate
private double monthlyServiceCharge; //Monthly service charge
/**
The constructor
Accept arguments for the balance and annual interest rate.
#param bal To hold the number of balance.
#param intRate To hold the number of annual interest rate.
#param mon To hold the number of monthly service charge.
*/
public BankAccount(double bal, double intRate, double mon)
{
balance = bal;
interestRate = intRate;
monthlyServiceCharge = mon;
}
/**
This method to hold the amount of deposit.
#param amount The amount of deposit.
*/
public void deposit(double amount)
{
balance = balance + amount;
numDeposits++;
}
/**
This method to hold the amount of withdrawal.
#param amount The amount of withdrawal.
*/
public void withdraw(double amount)
{
balance = balance - amount;
numWithdrawals++;
}
/**
This method to update the balance by calculating the monthly interest
earned by the account.
*/
private void calcInterest()
{
double monIntRate;
double monInt;
monIntRate = (interestRate / 12.0);
monInt = balance * monIntRate;
balance = balance + monInt;
}
/**
This method to calculate the monthly service charge.
*/
public void monthlyProcess()
{
balance = balance - monthlyServiceCharge;
calcInterest();
numWithdrawals = 0;
numDeposits = 0;
monthlyServiceCharge = 0;
}
/**
This method to hold the number of monthly service charge.
#param amount The number of monthly service charge.
*/
public void setMonthlyServiceCharges(double amount)
{
monthlyServiceCharge += amount;
}
/**
This method to return the amount of balance.
#return The amount of balance.
*/
public double getBalance()
{
return balance;
}
/**
This method to return the number of deposits.
#return The number of deposits.
*/
public int getNumDeposits()
{
return numDeposits;
}
/**
This method to return the number of withdrawals.
#return The number of withdrawals.
*/
public int getNumWithdrawals()
{
return numWithdrawals;
}
/**
This method to return the number of annual interest rate.
#return The number of annual interest rate.
*/
public double getInterestRate()
{
return interestRate;
}
/**
This method to return the amount of monthly service charge.
#return The amount of monthly service charge.
*/
public double getMonthlyServiceCharge()
{
return monthlyServiceCharge;
}
}
Subclass SavingsAccount.java
public class SavingsAccount extends BankAccount
{
private boolean status;
/**
The constructor
To accept the argument of balance, interest rate and monthly charge.
#param bal To hold the amount of balance.
#param intRate To hold the number of annual interest rate.
#param mon To hold the amount of monthly service charge.
*/
public SavingsAccount(double bal, double intRate, double mon)
{
super(bal, intRate, mon);
if (bal < 25)
{
status = false;
}
else
{
status = true;
}
}
/**
This method to determine whether the account is inactive before withdrawals
is made.
#param amount The amount of withdrawal.
*/
public void withdraw(double amount)
{
if (status = true)
{
super.withdraw(amount);
}
}
/**
This method to determine whether the account is inactive before a
deposit is made.
#param amount The amount of deposit.
*/
public void deposit(double amount)
{
if (status = true)
{
super.deposit(amount);
}
}
/**
This method to check the number of withdrawals.
*/
public void monthlyProcess()
{
if (getNumWithdrawals() > 4)
{
setMonthlyServiceCharges(getNumWithdrawals() - 4);
}
super.monthlyProcess();
if (getBalance() < 25)
{
status = false;
}
}
}
As the question above. I want to make only two withdraw because in the main program when I do 2 withdraw, the balance will become 20$ and it become inactive. But somehow my code did withdraw 5 times. So can someone give me an idea how to solve this problem. Thanks!
Change
public SavingsAccount(double bal, double intRate, double mon)
{
super(bal, intRate, mon);
if (bal < 25)
{
status = false;
}
else
{
status = true;
}
}
to
public void withdraw(double amount)
{
if (getBalance() > 25)
{
super.withdraw(amount);
}
}
and
public void withdraw(double amount)
{
if (status = true)
{
super.withdraw(amount);
}
}
to
public void withdraw(double amount)
{
if (getBalance() > 25)
{
super.withdraw(amount);
}
}
Ok I am having problems creating a transfer to method to transfer "money" from one account to the next. After the transfer the amounts of each account would be printed out. I created the code but when I run it the amount transferred is set to the bank account amount. It should just deduct from one account and add to the next account. What am I doing wrong?
This is my class with contructors and methods:
public class Account {
// Instance variables
private double balance;
// Constructors
public Account(double initialBalance) {
balance = initialBalance;
}
public Account(int account, double balance) {
this.balance = balance;
}
public Account() {
balance = 0.0;
}
// Instance methods
public void setBalance() {
balance = Math.random() * 1000;
balance = Math.round((balance * 100.0)+.5) / 100.0;
}
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
balance = balance - amount;
}
public double getBalance() {
balance = Math.round((balance * 100.0)+.5) / 100.0;
return balance;
}
public void close() {
balance = 0.0;
}
public void transferTo(Account bank, double x) {
if (x <= balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
} else if (x > balance) {
System.out.println("\nTransfer failed, not enough balance!");
}
}
}
This is my class with the main method
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
System.out.println("Accounts 1 balance is: $" + bank[0].getBalance());
System.out.println("Accounts 2 balance is: $" + bank[1].getBalance());
System.out.println("Accounts 3 balance is: $" + bank[2].getBalance());
System.out.println("Accounts 4 balance is: $" + bank[3].getBalance());
double x = Math.random()*100;
bank[0].transferTo(bank[1], x);
System.out.println("Remaining balance of Account 1: $" + bank[0].getBalance());
System.out.println("Remaining balance of Account 2: $" + bank[1].getBalance());
double y = (Math.random()*300);
bank[2].transferTo(bank[3], y);
System.out.println("Remaining balance of Account 3: $" + bank[2].getBalance());
System.out.println("Remaining balance of Account 4: $" + bank[3].getBalance());
}
}
One issue you did have, is that you were accidentally printing the BALANCE rather than the amount actually transferred, in your transferTo() method. I fixed this. On another note, if you're going to be printing these numbers out, look into printf() to make them appear as actual dollar amounts. I did it to one of the lines to show you an example.
PS - Try NOT using Math.random() for stuff when you're trying to debug.
public void transferTo(Account bank, double x) {
if (x <= this.balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + x);
} else { //does not need to be else if, because if not <=, it MUST be >.
System.out.println("\nTransfer failed, not enough balance!");
}
}
I can verify that the method works perfectly fine, after these edits, on my machine. This is what I used to test:
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
double x = 100.00;
System.out.printf("Transferring $%.2f from Acc 1 to Acc 2.\n", x); //printf example
System.out.println("Acc 1 previous balance: " + bank[0].getBalance());
System.out.println("Acc 2 previous balance: " + bank[1].getBalance());
bank[0].transferTo(bank[1], x);
System.out.println("Acc 1 new balance: " + bank[0].getBalance());
System.out.println("Acc 2 new balance: " + bank[1].getBalance());
}
}
And lastly, my output:
Transferring $100.00 from Acc 1 to Acc 2.
Acc 1 previous balance: 106.76
Acc 2 previous balance: 266.18
Transfer succesful. Transfered: $100.0
Acc 1 new balance: 6.77
Acc 2 new balance: 366.19
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
This prints the other account's new balance, because that's what you told it to do.
If you want to print the amount transferred:
System.out.println("\nTransfer succesful. Tansfered: $" + x);
// Bank account class
class BankAccount {
constructor(fname, lname, account_number) {
const minBalance = 10000;
this.name = `${fname} ${lname}`;
this.balance = minBalance;
this.account_number = account_number;
}
details() {
console.log(
`Cleint name: ${this.name} \n Balance: ${this.balance} \n Account number: ${this.account_number}`
);
}
isPositive(amount) {
return amount > 0 ? true : false;
}
isVlaidAmount(amount) {
return isNaN(amount) || !this.isPositive(amount) ? false : true;
}
deposit(amount) {
if (this.isVlaidAmount(amount)) {
this.balance += amount;
} else {
console.log("Sorry, this transcation cannot be completed!");
}
}
withdraw(amount) {
if (this.isVlaidAmount(amount)) {
this.balance -= amount;
} else {
console.log("Sorry, you have insufficient funds.");
}
}
transfer(amount, reciever) {
if (this.isVlaidAmount(amount)) {
this.withdraw(amount);
reciever.deposit(amount);
}
}
}
// create objects
let acc1 = new BankAccount("George", "Omara", 422);
let acc2 = new BankAccount("Haward", "Walowets", 662);
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);
}
}