java java简单的银行账户程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14521891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:32:14  来源:igfitidea点击:

java simple bank account program

javaclass

提问by Ahmad Dawod

I'm trying to build a simple bank account program that that subtract the withdrawal amount from the balance but when I call the deptmethod it's not doing the subtraction.

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

How to get this program to work, and I'm not sure if I should make the deptmethod void or make it return a value.

如何让这个程序工作,我不确定是否应该让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;
    } 
}

回答by Majid Laissi

Your deptmethod never updates the balance, but instead returns a value you never use.

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

You should update your balance:

您应该更新您的余额:

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

回答by user902383

your debt method return new value of balance but not setting it

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

what you could do is ie:

你可以做的是:

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

回答by FazoM

primitives like double are passed by value, not by reference. You are not changing value outside the debt method.

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

But yes - you are returning a value, but you don't assign it anywhere - try to assign it.

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

回答by Arpit

try this

试试这个

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

or change this function :

或更改此功能:

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