Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Constructor problem... JAVA

Options
  • 06-10-2012 10:18am
    #1
    Closed Accounts Posts: 2,663 ✭✭✭


    Im learning OOP with JAVA since im new to Java and most of the class is used to it where going way to fast. for my liking..

    we had a lab, every thing is working but cant get this part working
        public  boolean withdraw( double w ){
            withdraw = w;
            boolean ok;
            if(balance - w >= 0){
                balance = balance - w ;
                ok = true;
            } // end method if 
            else{ // open Else Statment, 
                System.out.printf("You dont have enough Money to Withdraw");
                ok = false;
            }// end method else 
            return(ok);
        }//end method Withdraw
    

    public String toString(){
            String str;
            str = "Your Name is:" + " " + getName() + "\n" +
                    "Your Starting Balance is:" + " " + balance + "\n" +
                "Your Account Number is:" + " " + getNumber() + " \n" +
                "Your Interest is:" + " " +  getInterest() + "\n" + 
                    "Your Deposit was:" + " " + getDeposit() + "\n" +
                    "Your Withdraw was:" + " " + withdraw + "\n" +
                "Your New Balance is:" + " " + getnBalance();
            return str;
    


    the problem i have its still withdrawing money and giving my new Balance as -100 euro, i want it to stop and output " You do not have enough money" in that case..


Comments

  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    Cork24 wrote: »
    Im learning OOP with JAVA since im new to Java and most of the class is used to it where going way to fast. for my liking..

    we had a lab, every thing is working but cant get this part working
        public  boolean withdraw( double w ){
            withdraw = w;
            boolean ok;
            if(balance - w >= 0){
                balance = balance - w ;
                ok = true;
            } // end method if 
            else{ // open Else Statment, 
                System.out.printf("You dont have enough Money to Withdraw");
                ok = false;
            }// end method else 
            return(ok);
        }//end method Withdraw
    

    public String toString(){
            String str;
            str = "Your Name is:" + " " + getName() + "\n" +
                    "Your Starting Balance is:" + " " + balance + "\n" +
                "Your Account Number is:" + " " + getNumber() + " \n" +
                "Your Interest is:" + " " +  getInterest() + "\n" + 
                    "Your Deposit was:" + " " + getDeposit() + "\n" +
                    "Your Withdraw was:" + " " + withdraw + "\n" +
                "Your New Balance is:" + " " + getnBalance();
            return str;
    


    the problem i have its still withdrawing money and giving my new Balance as -100 euro, i want it to stop and output " You do not have enough money" in that case..

    Looks like it should work.

    Output the values of balance and w before the If condition to see what they are


  • Registered Users Posts: 3,886 ✭✭✭cgarvey


    Cork24 wrote: »
    the problem i have its still withdrawing money and giving my new Balance as -100 euro, i want it to stop and output " You do not have enough money" in that case..

    Your 'withdraw' method works as you want it to, so check your use of the method, and check that something else is not setting the 'balance' member variable elsewhere.

    Are the values you are withdrawing non-integer? If so, are you running in to rounding issues (where 0.01 might not always be as you expect!). Take BrokenArrows's advice and print your values (before and after) to see. As an example if you start with a balance of 1.0, and withdraw 0.49 twice. You'd think you'd have 0.02 left, however it'll probably be something very slight above/below that value (0.020000000000000018 in my case). Compound that effect a few times, and you might end up with the issue you describe. I'm not sure that's likely to be the cause, however.

    Two tips that may help in future:
    1) Avoid naming member variables and methods the same thing. I.e. you appear to have "withdraw" as a class method (returns boolean), and as a class variable (of type double).
    2) Use "this" in front of instance variables. Whilst not strictly necessary, it's good practice. For example, in your "withdraw" method, use "this.balance" to refer to the class instance's member variable, and not just "balance". It's better practice, because it makes the code easier to understand, and can help with compiler warnings if you have duplicate variable names, etc.


  • Registered Users Posts: 240 ✭✭Axe Rake


    Cork24 wrote: »
    we had a lab, every thing is working but cant get this part working
        public  boolean withdraw( double w ){
            withdraw = w;
            boolean ok;
            if(balance - w >= 0){
                balance = balance - w ;
                ok = true;
            } // end method if 
            else{ // open Else Statment, 
                System.out.printf("You dont have enough Money to Withdraw");
                ok = false;
            }// end method else 
            return(ok);
        }//end method Withdraw
    

    First of all, it might be best to clean up your method a little bit :)

    This will make it easier to read and more logical:
    public boolean withdraw(double amount) {        
    
        // if our withdrawal amount is <= than what we have in our account
        if(amount <= balance) {
    
            balance -= amount; //withdraw the amount
            return true;
    
        } else { // withdrawal amount is > than balance
    
            System.out.printf("You dont have enough Money to Withdraw");
            return false;
        } 
    }
    


  • Closed Accounts Posts: 2,257 ✭✭✭GCU Flexible Demeanour


    cgarvey wrote: »
    Two tips that may help in future:
    1) Avoid naming member variables and methods the same thing. I.e. you appear to have "withdraw" as a class method (returns boolean), and as a class variable (of type double).
    2) Use "this" in front of instance variables. Whilst not strictly necessary, it's good practice. For example, in your "withdraw" method, use "this.balance" to refer to the class instance's member variable, and not just "balance". It's better practice, because it makes the code easier to understand, and can help with compiler warnings if you have duplicate variable names, etc.
    Just further on that, in your "toString" method, while you use getter methods to obtain the account number and some other details, you seem to be directly citing the "balance" and "withdraw(al)" variables. Its good practice to only operate on variables through (say) methods entitled "getBalance()" or "setBalance()".

    This has the benefit of avoiding what may be the problem in this case - the possibility that the variable is being changed by some other block of code. If they've mentioned the OOP concept of encapsulation to you, this is what it means in practice - making your variables private to the class, and only accessing them through particular methods, helps to protect your data from getting messed with.


  • Closed Accounts Posts: 2,663 ✭✭✭Cork24


    ok,

    This is the Full program..

    Class BANK ACCOUNT
    public class BankAccount {
     
        
        private String name;
        private int number;
        private double balance;
        private double deposit;
        private double withdraw;
        private double interest;
        private double nbalance;
        
        
            public BankAccount(String ip_name, double bal){
                name = ip_name;
                balance = bal;
                }
                public String getName(){
                return name;
                }
                
                public void number(int Acc){
                    number = Acc;
                    }
                
                    public int getNumber(){
                    return number;
                    }
                
                public void interest (double i){
                    
                    interest = i/100 * balance;
                }
    
                public double getInterest(){
                    return interest; 
                }
    
                public void Deposit(double d){
                    deposit = d;
                    }
    
                    public double getDeposit(){
                    return deposit;
                    }
    
        
        public  boolean withdraw( double w ){
            withdraw = w;
            boolean ok;
            if(balance - w >= 0){
                balance = balance - w ;
                System.out.println("You have Withdraw:");
                ok = true;
            } // end method if 
            else{ // open Else Statment, 
                System.out.println("You dont have enough Money to Withdraw");
                ok = false;
            }// end method else 
            return(ok);
        }//end method Withdraw
        
        
    
        
        
        public void nbalance(double nbal){
            nbalance = balance + deposit + interest - withdraw; 
         } // end method nbalance
        
        public double getnBalance(){
        return nbalance;
        }//end method getnBalance
        
        
        
        public String toString(){
            String str;
            str = "Your Name is:" + " " + getName() + "\n" +
                    "Your Starting Balance is:" + " " + balance + "\n" +
                "Your Account Number is:" + " " + getNumber() + " \n" +
                "Your Interest is:" + " " +  getInterest() + "\n" + 
                    "Your Deposit was:" + " " + getDeposit() + "\n" +
                    "Your Withdraw was:" + " " + withdraw + "\n" +
                "Your New Balance is:" + " " + getnBalance();
            return str;
        }//end method String
        
        }//end class BankAccount
    

    Bank Account Test;
    public class AccountTest {
        public static void main(String[] args){
        BankAccount account1, account2Account, account3;
    
        account1 = new BankAccount("David", 500);
        account1.number(230);
        account1.interest(.3);
        account1.Deposit(800);
        account1.withdraw(800);
        account1.nbalance(0);
        System.out.print(account1.toString()+"\n");
    
        
        
        
    }
    }
    
    


  • Advertisement
  • Registered Users Posts: 203 ✭✭Sherfin


    I think the problem is in your withdraw() method. When you try to withdraw(800) you are setting your withdraw variable to 800, but what happens if there is not enough money in the account ? When you go to calculate your balance and print your account.toString() it still has the 800 vaue


  • Closed Accounts Posts: 2,663 ✭✭✭Cork24


    Sherfin wrote: »
    I think the problem is in your withdraw() method. When you try to withdraw(800) you are setting your withdraw variable to 800, but what happens if there is not enough money in the account ? When you go to calculate your balance and print your account.toString() it still has the 800 vaue


    When i withdraw 800 its given me 500 left in the account,

    But when i withdraw more then whats in the account it goes to negative number.


  • Registered Users Posts: 8,324 ✭✭✭chrislad


    Try if ((balance - w) >= 0) rather than (balance - w >= 0)


  • Moderators, Technology & Internet Moderators Posts: 1,334 Mod ✭✭✭✭croo


    When i withdraw 800 its given me 500 left in the account,

    But when i withdraw more then whats in the account it goes to negative number.
    I think you misunderstand what Sherfin is telling you...

    If your code was
    	    account1.withdraw(1500);
    	    account1.nbalance(0);
    	    System.out.print(account1.toString()+"\n");
    
    When you call withdraw using 1500 you *will* get the message that "You don't have enough Money..."

    But the attribute "withdraw" has still been set
    public  boolean withdraw( double w ){
            withdraw = w;
    ...
    ...
    
    Now you run nbalance with zero - which by the way makes little sense. You pass a value that is never used!
    When you do this the nbalance is set as
    nbalance = balance + deposit + interest - withdraw;
    
    So even though the withdraw method failed you are still updating the balance because the attribute withdraw has been set to 1500.

    I would echo what others have said
    * using methods & attributes with the same names will only make debugging more difficult.
    * look again at the idea of encapsulation


  • Registered Users Posts: 183 ✭✭selfdiy


    Just as a side note. When dealing with money numbers, use BigDecimals as doubles are not accurate enough.


  • Advertisement
  • Registered Users Posts: 7,157 ✭✭✭srsly78


    selfdiy wrote: »
    Just as a side note. When dealing with money numbers, use BigDecimals as doubles are not accurate enough.

    Double is fine for currency, float would be fine as well. Only need more accuracy for scientific calculations.


  • Registered Users Posts: 11,979 ✭✭✭✭Giblet


    srsly78 wrote: »
    Double is fine for currency, float would be fine as well. Only need more accuracy for scientific calculations.

    Absolutely false. Simple operations such as rounding after subtracting a percentage can cause issues.


  • Registered Users Posts: 1,082 ✭✭✭Feathers


    srsly78 wrote: »

    Double is fine for currency, float would be fine as well. Only need more accuracy for scientific calculations.

    Well, you could say you need them for accuracy for currency, but for precision for science ;)

    I thought the idea of BigDecimal for currency was to avoid rounding errors?


  • Registered Users Posts: 183 ✭✭selfdiy


    srsly78 wrote: »
    Double is fine for currency, float would be fine as well. Only need more accuracy for scientific calculations.


    Many years ago I found out the hard way that they are not fine... ;)

    Take a look here

    http://www.mkyong.com/java/how-do-calculate-monetary-values-in-java-double-vs-bigdecimal/

    BigDecimals are slower operating then primitive types, but when dealing with currencies accuracy is everything.


  • Registered Users Posts: 7,157 ✭✭✭srsly78


    Not false at all. Yes you have to watch out for rounding, but float maths is used all over finance. You should go into some investment bank and tell them they are doing it wrong :)


  • Moderators, Technology & Internet Moderators Posts: 1,334 Mod ✭✭✭✭croo


    srsly78 wrote: »
    Not false at all. Yes you have to watch out for rounding, but float maths is used all over finance. You should go into some investment bank and tell them they are doing it wrong :)
    That could explain a lot! :P

    I've never seen java business software that uses double instead of Bigdecimal. Just google it the web is full of it. Or try it yourself
    public class BigDecimalExample {
     
        public static void main(String args[]) throws IOException {
          
          //floating point calculation
          double amount1 = 2.15;
          double amount2 = 1.10;
          System.out.println("difference between 2.15 and 1.0 using double is: " + (amount1 - amount2));
        
          //Use BigDecimal for financial calculation
          BigDecimal amount3 = new BigDecimal("2.15");
          BigDecimal amount4 = new BigDecimal("1.10") ;
          System.out.println("difference between 2.15 and 1.0 using BigDecimal is: " + (amount3.subtract(amount4)));      
        }     
    }
    Output:
    difference between 2.15 and 1.0 using double is: 1.0499999999999998
    difference between 2.15 and 1.0 using BigDecmial is: 1.05
    
    Read more: http://javarevisited.blogspot.com/2012/02/java-mistake-1-using-float-and-double.html#ixzz29U3lWz8d
    


  • Registered Users Posts: 880 ✭✭✭clearz


    Try this to set you on the right track
    class BankAccount {
    
        private String name;
        private int accountNumber;
        private double balance;
        private double deposit;
        private double lastWithdrawl;
        private double interest;
        private double nbalance;
    
    
        public BankAccount(String name, double bal){
            this.name = name;
            this.balance = bal;
        }
    
        public double getBalance()
        {
            return balance;
        }
    
        public String getName(){
            return this.name;
        }
    
        public void setAccountNumber(int num){
            this.accountNumber = num;
        }
    
        public int getAccountNumber(){
            return this.accountNumber;
        }
    
        public void setInterest (double i){
            this.interest = i/100 * balance;
        }
    
        public double getInterest(){
            return this.interest;
        }
    
        public void setDeposit(double d){
            this.deposit = d;
        }
    
        public double getDeposit(){
            return this.deposit;
        }
    
    
        public  boolean withdraw( double w ){
    
            System.out.println("Withdrawing: EUR " + w);
            if(w <= balance){
                balance -= w ;
                System.out.println("You have Withdrawn: EUR " + w);
                lastWithdrawl = w;
                return true;
            } // end method if
    
            System.out.println("You dont have enough Money to Withdraw");
            return false;
    
        }//end method Withdraw
    
    
    
    
    
        public void updateBalance(){
            System.out.println("Updating Balance");
            balance = balance + deposit + interest - lastWithdrawl;
         } // end method nbalance
    
    
    
    
        public String toString(){
            String str;
            str = "Your Name is:" + " " + getName() + "\n" +
                    "Your Starting Balance is:" + " " + getBalance() + "\n" +
                "Your Account Number is:" + " " + getAccountNumber() + " \n" +
                "Your Interest is:" + " " +  getInterest() + "\n" +
                    "Your Deposit was:" + " " + getDeposit() + "\n" +
                    "Your Withdraw was:" + " " + lastWithdrawl + "\n" +
                "Your New Balance is:" + " " + getBalance();
            return str;
        }//end method String
    
    }//end class BankAccount
    
    public class AccountTest {
    
        public static void main(String[] args){
            BankAccount account1, account2Account, account3;
    
            account1 = new BankAccount("David", 500);
            account1.setAccountNumber(230);
            account1.setInterest(.3);
            account1.setDeposit(800);
            account1.withdraw(800);
    
            System.out.println(account1.toString()+"\n");
            account1.updateBalance();
    
            System.out.println("Your New Balance is: "+ account1.getBalance());
    
            account1.withdraw(800);
    
            System.out.println("Your New Balance is: "+ account1.getBalance());
        }
    }
    


  • Registered Users Posts: 1,082 ✭✭✭Feathers


    clearz wrote: »
    Try this to set you on the right track
    class BankAccount {
    
        private String name;
        private int accountNumber;
        private double balance;
        private double deposit;
        private double lastWithdrawl;
        private double interest;
        private double nbalance;
    
    
        public BankAccount(String name, double bal){
            this.name = name;
            this.balance = bal;
        }
    
        public double getBalance()
        {
            return balance;
        }
    
        public String getName(){
            return this.name;
        }
    
        public void setAccountNumber(int num){
            this.accountNumber = num;
        }
    
        public int getAccountNumber(){
            return this.accountNumber;
        }
    
        public void setInterest (double i){
            this.interest = i/100 * balance;
        }
    
        public double getInterest(){
            return this.interest;
        }
    
        public void setDeposit(double d){
            this.deposit = d;
        }
    
        public double getDeposit(){
            return this.deposit;
        }
    
    
        public  boolean withdraw( double w ){
    
            System.out.println("Withdrawing: EUR " + w);
            if(w <= balance){
                balance -= w ;
                System.out.println("You have Withdrawn: EUR " + w);
                lastWithdrawl = w;
                return true;
            } // end method if
    
            System.out.println("You dont have enough Money to Withdraw");
            return false;
    
        }//end method Withdraw
    
    
    
    
    
        public void updateBalance(){
            System.out.println("Updating Balance");
            balance = balance + deposit + interest - lastWithdrawl;
         } // end method nbalance
    
    
    
    
        public String toString(){
            String str;
            str = "Your Name is:" + " " + getName() + "\n" +
                    "Your Starting Balance is:" + " " + getBalance() + "\n" +
                "Your Account Number is:" + " " + getAccountNumber() + " \n" +
                "Your Interest is:" + " " +  getInterest() + "\n" +
                    "Your Deposit was:" + " " + getDeposit() + "\n" +
                    "Your Withdraw was:" + " " + lastWithdrawl + "\n" +
                "Your New Balance is:" + " " + getBalance();
            return str;
        }//end method String
    
    }//end class BankAccount
    
    public class AccountTest {
    
        public static void main(String[] args){
            BankAccount account1, account2Account, account3;
    
            account1 = new BankAccount("David", 500);
            account1.setAccountNumber(230);
            account1.setInterest(.3);
            account1.setDeposit(800);
            account1.withdraw(800);
    
            System.out.println(account1.toString()+"\n");
            account1.updateBalance();
    
            System.out.println("Your New Balance is: "+ account1.getBalance());
    
            account1.withdraw(800);
    
            System.out.println("Your New Balance is: "+ account1.getBalance());
        }
    }
    

    Won't this subtract the withdrawal amount both on withdraw() and updateBalance() methods?

    Also, seems strange to have getDeposit methods on a Bank Account alongside another method to read the balance…


  • Registered Users Posts: 880 ✭✭✭clearz


    @Feathers
    The whole class is hideous to begin with. The code is meant as a push in the right direction than a completion of homework.


Advertisement