编写一种方法,从特定客户的帐户中提取资金并返回帐户余额。如果帐户上没有足够的钱,该方法将返回-1
方法的签名 - withdraw (String [] clients, int [] balances, String client, int amount)
package Lesson5;
/**
* Created by Ruslan on 12.06.2017.
*/
public class takeOffBalance {
public static void main(String[] args) {
String clients[] = {"John", "Pedro", "Valera", "Muchachos", "Vovan"};
int [] balances = {1, 100, 3500, 222, 1234};
System.out.println(withdraw(clients, balances, "Pedro", (int) 10000));
}
static int withdraw(String[] clients, int[] balances, String client, int amount) {
int res = balances[findClient(clients, client)] - amount;
return res >= 0 ? res : -1;
}
static int findClient (String [] clients, String client) {
int clientIndex = 0;
for (String name : clients) {
if (name == client) {
break;
}
clientIndex++;
}
return clientIndex;
}
}
答案 0 :(得分:0)
请尝试以下方法。你应该检查负数和余额。看起来有一个失败的负面测试。
static int withdraw(String[] clients, int[] balances, String client, int amount) {
int index = findClient(clients, client);
if (index == -1) // no client found
return -1;
// Negative balance, negative amount and insufficient credit.
if(balances[index] < 0 || amount < 0 || balances[index] - amount < 0)
return -1;
return balances[index] - amount;
}
static int findClient (String [] clients, String client) {
int clientIndex = 0;
for (String name : clients) {
if (null != name && name.equals(client)) {
break;
}
clientIndex++;
}
return -1; //no client found
}
答案 1 :(得分:0)
您必须检查负数,如果帐户不存在,也不会检查案例。您需要添加所有这些验证才能使其正常工作。