5

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.

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
PrimalScientist
  • 831
  • 5
  • 17
  • 27
  • 1
    This is not python. Place brackets for your ifs – Boris Strandjev May 13 '13 at 10:20
  • I used to but was advised that it is not required? – PrimalScientist May 13 '13 at 10:20
  • 1
    That was some very bad advice. – Marko Topolnik May 13 '13 at 10:21
  • Thank you for your feedback and will amend immediately. – PrimalScientist May 13 '13 at 10:21
  • 1
    Your debit and credit methods should return a boolean. – MosesA May 13 '13 at 10:21
  • 2
    @PrimalScientist Its not required if you only need to execute one statement. Even though, its always recommended to use them – Evans May 13 '13 at 10:22
  • 2
    Never use `==` for String comparison. Use `equals()`. – Axel May 13 '13 at 10:22
  • Many thanks. Although they should return a boolean, I am unsure how to return this and an amount? Or should the amount just be amended else where in the code? – PrimalScientist May 13 '13 at 10:22
  • Great comments here. Thank you for all feedback. Will amend as shown. – PrimalScientist May 13 '13 at 10:23
  • 1
    It says **update and return a false** so you don't have to return the new balance just a boolean value. – MosesA May 13 '13 at 10:24
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo May 13 '13 at 10:25
  • 1
    @PrimalScientist regarding returning a boolean and a number; you shouldn't really need to, you don't appear to be using the returned value currently anyway. However, if in the future you must return multiple objects you can wrap them up in a single 'Container' object which contains the multiple return objects (Its still a class but it behaves like a struct from other languages) – Richard Tingle May 13 '13 at 10:30
  • @alex23 Good point. I am using Spring and as I was going through the code it highlighted to make this amendment so I did. By doing this removed errors that were in the if statements? – PrimalScientist May 13 '13 at 10:31
  • 1
    Good point. Originally the variables were not static. I am beginning to understand now. Its amazing how much you can learn from posting this sort of question! I was not sure whether to at first but I am glad I did, brilliant feedback. – PrimalScientist May 13 '13 at 10:34

7 Answers7

6

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

}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
3

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.

Joetjah
  • 6,292
  • 8
  • 55
  • 90
  • @Joetjah Note; in your answer you are still using string == which will not work: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Richard Tingle May 13 '13 at 10:25
  • This is brilliant, thank you. Once I get this part of the code working I will begin to look at the boolean side. However, how can I also return true or false with a value? I found the question a good question but I am a little confused how to tackle this? – PrimalScientist May 13 '13 at 10:29
  • 1
    Well, what you can do is only return a boolean, since your `currentBalance` is class-wide anyway, you can get the change of money. Like so: `if (debit(currentBalance, amount)) { System.out.println("Your money has been decreased to " + currentBalance); } else { System.out.println("Transaction cancelled."); }` – Joetjah May 13 '13 at 10:31
  • 2
    If you really want to return 2 values, you have to create an object or class that encapsulates both. http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method I wouldn't do that in this setting though. – Joetjah May 13 '13 at 10:32
2
if (userInput == deposit)

should be

if (userInput.equals(deposit))

Same for withdrawal.

Axel
  • 13,939
  • 5
  • 50
  • 79
2

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

Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
  • Many thanks for your feedback. How else could I amend the currentBalance variable though? Or would by returning the amount do this automatically? – PrimalScientist May 13 '13 at 10:47
  • @PrimalScientist I've updated my answer to answer as an example but basically a non static method can access any non static field of the class (i.e. any account method can access accountNumber and currentBalance). Thats one of the founding principles of Object Orientated code – Richard Tingle May 13 '13 at 11:00
  • Yes I see this now. Quick question Richard, here you have created a new object: Account acc=new Account(1234,1000); So this is the account number and the amount in the bank. I could also amend the code to take user input and amend accordingly. – PrimalScientist May 13 '13 at 17:04
  • 1
    Of course, the most sensible way would probably be to ask the user for that information and then create the object using the constructor. But you could equally create a blank constructor and them give it the information piece by piece. The choice is yours but its generally considered good practice for an object to recieve the information it needs to work in the constructor (so an object is garanteed to work if it exists, rather than "You've forgotton to to call these 3 methods after construction hence your problem") – Richard Tingle May 13 '13 at 17:19
1

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)

Shane
  • 2,315
  • 3
  • 21
  • 33
1

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

}
}
Korhan Ozturk
  • 11,148
  • 6
  • 36
  • 49
Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50
1

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.

MosesA
  • 925
  • 5
  • 27
  • 53