java简单的银行帐户程序

时间:2013-01-25 12:32:17

标签: java class

我试图构建一个简单的银行帐户程序,从余额中减去提款金额但是当我调用 dept 方法时,它没有进行减法。

如何让这个程序运行,我不确定是否应该使 dept 方法无效或让它返回一个值。

    import java.util.Scanner;
    public class JavaApplication7 {

    public static void main(String[] args) {
        Scanner input = new Scanner( System.in );

        Account account1 = new Account( 50.0 ); 

        System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );

        double withdrawalAmount;

        System.out.print( "Enter withdrawal amount for account1: " );

        withdrawalAmount = input.nextDouble();

        System.out.printf( "\nsubtracting %.2f from account1 balance\n", withdrawalAmount );

        account1.dept(withdrawalAmount);

        System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );
    }

}

public class Account {
    private double balance; // instance variable that stores the balance

    public Account( double initialBalance )
    {

        if ( initialBalance > 0.0 )
            balance = initialBalance;
        } 

        public double dept (double dept1){

        dept1=balance-dept1;    
        return dept1;    
    }


    public double getBalance()
    {
        return balance;
    } 
}

4 个答案:

答案 0 :(得分:2)

您的dept方法永远不会更新余额,而是返回您从未使用过的值。

您应该更新余额:

public void dept (double dept1){
    balance=balance-dept1;    
}

答案 1 :(得分:1)

你的债务方法返回新的余额值而不是设定它

你能做的就是:

public void dept (double dept1){
balance-=dept1;    
}

答案 2 :(得分:0)

像double这样的原语是按值传递的,而不是通过引用传递的。你不会在债务法之外改变价值。

但是 - 你正在返回一个值,但你没有在任何地方分配它 - 尝试分配它。

答案 3 :(得分:0)

试试这个

System.out.println("New Balence is : "+account1.dept(withdrawalAmount));

或更改此功能:

public void dept (double dept1){
    balance=balance-dept1;        
    }