【问题标题】:Trouble undestanding this piece of code from codeAcademy Java methods无法从 codecademy Java 方法中理解这段代码
【发布时间】:2022-09-23 01:45:27
【问题描述】:

有人可以向我解释为什么在withdraw() 中需要添加return,但在deposit() 中不需要它?

public class SavingsAccount {
  
  int balance;
  
  public SavingsAccount(int initialBalance){
    balance = initialBalance;
  }
  
  public void checkBalance(){
    System.out.println(\"Hello!\");
    System.out.println(\"Your balance is \" + balance);

  }

  public void deposit(int amountToDeposit){
    balance = balance + amountToDeposit;
    System.out.println(\"You just deposited \" + amountToDeposit); 

  }

  public int withdraw(int amountToWithdraw){
    balance = balance - amountToWithdraw;
    System.out.println(\"You just withdrew \" + amountToWithdraw);
    return amountToWithdraw;

  }

  public static void main(String[] args){
    SavingsAccount savings = new SavingsAccount(2000);
    

    //Withdrawing:
    savings.withdraw(150);
    
    //Deposit:
    savings.deposit(25);
    
    //Check balance:
    savings.checkBalance();
    
  }       
}

    标签: java


    【解决方案1】:

    这是因为在 withdraw() 方法的定义中,声明它应该返回一个 int。 在 deposit() 方法中,您使用 void 作为返回类型。使用 void 时,不需要 return。 (但如果你愿意,你仍然可以在方法的末尾使用一个空的return;

    【讨论】:

      【解决方案2】:

      return 关键字的意思是“将此值返回给调用者”。

      withdraw() 给调用者一个intdeposit() 不给调用者任何东西。由于deposit() 不会将任何信息返回给调用者,因此return 不会提供任何信息。你可以在函数签名- deposit()返回类型void,而withdraw()返回类型int

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-21
        • 1970-01-01
        • 2012-10-24
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        • 2017-10-04
        • 1970-01-01
        相关资源
        最近更新 更多