-2

Write a method that will withdraw money from a particular customer's account and return the balance on the account. If there is not enough money on the account, the method will return -1

The signature of the method - 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;
    }


}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

2 Answers2

0

Please try the following. You should check for negative amount and balances. It looks like there is a negative test that is failing.

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
}
damjad
  • 1,252
  • 1
  • 15
  • 24
0

You have to check for negative amounts, also there is no check for the case if account doesn't exist. You need to add all these validations to make it work properly.

Bhanu Boppana
  • 134
  • 1
  • 2
  • 10