如何读取相同类型的两个参数?

时间:2016-01-21 03:11:23

标签: java

我正在尝试创建一种方法,将资金从一个帐户转移到另一个帐户..

我正在尝试将帐户类的发送和接收帐号都作为输入参数,但我收到了无效的帐号例外。

如何在不产生异常的情况下执行此操作? 有没有办法将这两个参数都设为'accountNumber'?

public int fundTransfer(int accountNumber, int accountNumber1, int amount) throws InvalidAccountNumberException, InsufficientBalanceException{

    Account account=searchaccount(accountNumber);
    Account account1= searchaccount(accountNumber1);

    if(amount>0){
        account.setAmount(account.getAmount()-amount);
        account1.setAmount(account1.getAmount()+amount);
    }else{
        throw new InsufficientBalanceException();
    }

    throw new InvalidAccountNumberException();
}

2 个答案:

答案 0 :(得分:0)

每次调用此方法时都会运行

throw new InvalidAccountNumberException();,因为它位于if else语句集群之外。

试试这个:

public int fundTransfer(int accountNumber, int accountNumber1, int amount) throws InvalidAccountNumberException, InsufficientBalanceException{

        Account account=searchaccount(accountNumber);
        Account account1= searchaccount(accountNumber1);

        if(amount>0){
            account.setAmount(account.getAmount()-amount);
            account1.setAmount(account1.getAmount()+amount);
        }else{
            throw new InsufficientBalanceException();
        }

           // throw new InvalidAccountNumberException();
    }
}

答案 1 :(得分:0)

以下是我对您可以更改的代码的看法:

public int fundTransfer(int accountNumber, int accountNumber1, int amount) throws InvalidAccountNumberException, InsufficientBalanceException{

    Account account=searchaccount(accountNumber);
    Account account1= searchaccount(accountNumber1);

    if(amount>0){
        account.setAmount(account.getAmount()-amount);
        account1.setAmount(account1.getAmount()+amount);
    }else{
        throw new InsufficientBalanceException();
    }
}

并将throw new InvalidAccountNumberException();放在searchaccount函数