-2

我正在尝试构建一个简单的银行账户程序,该程序从余额中减去提款金额,但是当我调用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

4 回答 4

2

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

您应该更新余额:

public void dept (double dept1){
    balance=balance-dept1;    
}
于 2013-01-25T12:34:56.223 回答
1

您的债务方法返回新的余额值但不设置它

你可以做的是:

public void dept (double dept1){
balance-=dept1;    
}
于 2013-01-25T12:35:28.323 回答
0

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

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

于 2013-01-25T12:35:59.940 回答
0

尝试这个

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

或更改此功能:

public void dept (double dept1){
    balance=balance-dept1;        
    }
于 2013-01-25T12:40:17.197 回答