我的存取款方式无法正常使用?我对此很陌生。我哪里犯了错误? [已关闭]

问题描述 投票:0回答:1
import java.util.Scanner;

public class Account {
    static double balance;

    public Account(double startingBalance) {
        balance = startingBalance;
    }
    // deposit method
    public void deposit(double amountToDeposit) {
        double updatedBalance;
        updatedBalance = balance + amountToDeposit;
        balance = updatedBalance;
    }

    // withdrawal method
    public void withdraw(double amountToWithdraw) {
        double updatedBalance;
        updatedBalance = balance - amountToWithdraw;
        balance = updatedBalance;

    }

    // main codebase
    public static void main(String[] args) {
        Account myAccount = new Account(balance);
        // ask input
        Scanner myObj = new Scanner(System.in);
        System.out.println("Enter starting balance:");

        // double input for balance
        //  is equal to input scanned
        double balance = myObj.nextDouble();

        // withdraw or deposit?
        Scanner my_decision = new Scanner(System.in);
        System.out.println("Would you like to make a deposit or withdrawal?");
        String decision = my_decision.nextLine();

        // conditional statements
        if (decision.contentEquals("withdrawal")){
            Scanner myWithdrawal = new Scanner(System.in);
            System.out.println("Withdrawal Amount:");
            double withdrawalAmount = myWithdrawal.nextDouble();

            myAccount.withdraw(withdrawalAmount);
            System.out.println("Your balance is: " + balance);

        } else if (decision.contentEquals("deposit")) {
            Scanner myDeposit = new Scanner(System.in);
            System.out.println("Deposit amount:");

            double depositAmount = myDeposit.nextDouble();

            myAccount.deposit(depositAmount);
            System.out.println("Your balance is: " + balance);
        }

    }
}

当我说存款时,我会输入我要存入的金额,希望程序将存款金额添加到余额中,但它只是打印出原始余额,没有任何变化。我提款时也是如此。我将输入要提取的金额,但程序不会从余额中扣除。

我想我可能错误地使用了扫描仪功能。

java methods java.util.scanner
1个回答
0
投票

您有两个名称相似的变量; 平衡

static double balance;

还有,

double balance = myObj.nextDouble();

将您的类字段 balance 分配给 myObj.nextDouble()

balance = myObj.nextDouble();

这是一个示例输出。

Enter starting balance:
100
Would you like to make a deposit or withdrawal?
withdrawal
Withdrawal Amount:
1.23
Your balance is: 98.77
Enter starting balance:
100
Would you like to make a deposit or withdrawal?
deposit
Deposit amount:
1.23
Your balance is: 101.23
© www.soinside.com 2019 - 2024. All rights reserved.