嗨,我是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/