java - 对象作为参数

标签 java

嗨,我是java程序员的新手,也是我们大学的新生。我目前正在练习我的java程序,遇到了一个问题,我不知道如何编写代码,其中我有一个对象作为参数并希望有一个值。

public int transferTo(Account another, int amount)
{
   if (amount<=balance)
     // I dont know how to use the object another to have the value of amount put into the object.
     // another = amount; it causes a compiler error

}

希望得到有见地的回应<3

最佳答案

Your transferTo(Account another, int amount) method will do something like this.

public int transferTo(Account another, int amount) throws Exception{  
 if(another==null){
  throw new NullPointerException("To Account Cannot be Null"); 
 }

 if(this.getBal()> amount){  
  this.setBal(this.getBal() - amount);
  another.setBal(another.getBal() + amount);
 }else{
   throw new InsufficientFundsException("Insufficient funds! for " + this.id + ": "  + this.name );
 }
  return this.getBal(); // return total balance of account;
}

您可以创建一个名为InsufficientFundsException.class的类并声明如下

class InsufficientFundsException extends Exception {
   public InsufficientFundsException(String msg){
        super(msg);
   }
}

关于java - 对象作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59479003/

相关文章:

java - 找不到正确的 JIRA Java SDK 版本的问题

java - 更改spring security中的登录服务URL

java - 国际象棋主教的实现规则

Java组合框 Swing

java - 在多线程Java程序中计时远程调用

java - Android ScrollView填充60%

java - Spring Roo : Deleting from DB?

java - 数字总和,直到总和为一位数

java - 为什么Chrome Java更新会在64位计算机上安装全局32位JRE?

java - 对非构造函数方法强制执行 super 调用