【问题标题】:how to fix this code to meet the requirements? [closed]如何修复此代码以满足要求? [关闭]
【发布时间】:2021-07-24 10:51:17
【问题描述】:

我的代码

主要:

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

        acc.acc1 = 1123.979;
        acc.acc2 = 543.758;

        System.out.println("account1 balance: " + "$" + acc.acc1);
        System.out.println("account2 balance: " + "$" + acc.acc2);

        System.out.println();

        System.out.print("Enter amount for account1: ");
        acc.WAmount1 = input.nextInt();;
        System.out.println();
        System.out.println("Subtracting " + acc.WA1 + " from account1 balance");
        acc.debit();

        System.out.println();

        System.out.print("Enter amount for account2: ");
        acc.WAmount2 = input.nextInt();

        System.out.println();

        System.out.println("Subtracting " + acc.WA2 + " from account2 balance");

        acc.Debit();
    }
}

我测试了代码,它运行良好。问题出在代码上,我认为指令说我只能在Account 类中提供一种方法,即 wdraw

【问题讨论】:

    标签: java object oop methods


    【解决方案1】:

    一个 Account 类应该只包含一个金额字段。如果您有多个帐户,则创建同一个类的新实例,因此每个实例都保存一个帐户的信息,并且只保存一个帐户。

    提款方法应以提款金额为参数,因为提款金额不是账户的固有部分,而是与一次提款操作相关的临时值

    类似

    public class Account {
      double amount;
    
      public void withdraw(double withdrawal){
         if (amount - withdrawal< 0){
            System.out.println("the debit amount exceeded the account balance");
         } else { 
             amount-=withdrawal;
         }
         System.out.println("account balance: $" + amount);
      }
    }
    

    如果可能(足够的资金),请不要忘记通过提款来减少金额。

    然后您可以实例化多个帐户:

    Account account1=new Account();
    // set amount and do withdrawals on account1
    
    Account account2=new Account();
    // set amount and do withdrawals on account2
    

    【讨论】:

    • JP Moresmau 如果您能完成帐户类中的方法,我可以请您帮忙吗?我无法分析它。
    • 添加了非常基本的实现,适应你的需求
    • JP Morescau 你试过代码吗?因为当我把你提供的实现输出是错误的。你能帮我完成吗,因为我真的不明白代码缺少什么。我
    • 它只显示账户 1 的输出。我需要另一个实现吗?我还是解决不了
    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2011-09-18
    相关资源
    最近更新 更多