Why does -1000 >= -1000 get interpreted as false in this code? - java

I was working on an exercise in a Java programming book for beginners where I had to create a bank account with a withdraw limit of up to -1000 Euros. Somehow, even though the amount is -1000 Euros, the code executes the else code, which for me makes little sense. It shouldn't output the error in my opinion, but it does.
Here is the account code:
public class Account {
private String accountnumber;
protected double accountbalance;
Account(String an, double ab) {
accountnumber = an;
accountbalance = ab;
}
double getAccountbalance() {
return accountbalance;
}
String getAccountnumber() {
return accountnumber;
}
void deposit(double ammount) {
accountbalance += ammount;
}
void withdraw(double ammount) {
accountbalance -= ammount;
}
}
The extended account:
public class GiroAccount extends Account{
double limit;
GiroAccount(String an, double as, double l) {
super(an, as);
limit = l;
}
double getLimit() {
return limit;
}
void setLimit(double l) {
limit = l;
}
void withdraw(double ammount) {
if ((getAccountbalance() - ammount) >= limit) {
super.withdraw(ammount);
} else {
System.out.println("Error - Account limit is exceded!");
}
}
}
The code to test the accounts:
public class GiroAccountTest {
public static void main(String[] args) {
GiroAccount ga = new GiroAccount("0000000001", 10000.0, -1000.0);
ga.withdraw(11000.0);
System.out.println("Balance: " + ga.getAccountbalance());
ga.deposit(11000.0);
ga.withdraw(11001.0);
System.out.println("Balance: " + ga.getAccountbalance());
}
}
The output:
Balance: -1000.0
Error - Account limit is exceded!
Balance: 10000.0

Let's take step by step.
1. Start with 10000.0;
2. withdraw(11000.0) -> -1000.0
3. Print balance -> "Balance: -1000.0"
4. deposit(11000.0) -> 10000.0
5. withdraw(11001.0); -> -1001.0 < -1000.0
6. Overdrawn (enters else block) -> "Error - Account limit is exceeded"
7. Print balance -> "Balance: 10000.0"
If I'm wrong please correct me.

Related

Print only non-negative balance in Java

I'm currently solving the PaymentCard exercise in https://java-programming.mooc.fi/part-4/1-introduction-to-object-oriented-programming and the output of this program should not be a negative balance. If ever the balance gets negative, it will not be printed. I added a conditional statement in both methods but my output keeps printing a negative balance.
Any help would genuinely be appreciated. Thanks!
//Desired Output:The card has a balance 5.0 euros
// The card has a balance 0.40000000000000036 euros
// The card has a balance 0.40000000000000036 euros
//My Output: The card has a balance of 5.0 euros
// The card has a balance of 0.40000000000000036 euros
// The card has a balance of -4.199999999999999 euros
public class MainProgram {
public static void main(String[] args) {
PaymentCard card = new PaymentCard(5);
System.out.println(card);
card.eatHeartily();
System.out.println(card);
card.eatHeartily();
System.out.println(card);
}
}
public class PaymentCard {
private double balance;
public PaymentCard(double openingBalance) {
this.balance = openingBalance;
}
public String toString() {
return "The card has a balance of " + this.balance + " euros";
}
public void eatAffordably() {
if (this.balance > 0) {
this.balance = this.balance - 2.60;
}
}
public void eatHeartily() {
if (this.balance > 0) {
this.balance = this.balance - 4.60;
}
}
}
Obviously you can print only amount greater then zero, but
I think a more correct and elegant solution is take into consideration also the amount you subtract:
public void eatAffordably() {
if (this.balance >= 2.60) {
this.balance = this.balance - 2.60;
}
}
public void eatHeartily() {
if (this.balance >= 4.60) {
this.balance = this.balance - 4.60;
}
}
Rather than having a toString method
public String toString() {
return "The card has a balance of " + this.balance + " euros";
}
and calling System.out.println(card);
create a method that does the actual printing e.g.
void printCard () {
if (this.balance > 0) {
System.out.println(card);
}
}

Account and Test Account Interest class

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.

Bank Account TransferTo Method

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);

Add numbers in JAVA

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

If statement is being missed in Bank Account Class?

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);
}
}

Categories

Resources