2017-06-13 16 views
-2

編寫一個方法,將從特定客戶的賬戶中提取資金並返回賬戶餘額。如果沒有足夠的資金賬戶上,該方法將返回-1錯誤「<-1>但是:<2147483647>」。請告訴我,代碼有什麼問題?

方法的簽名 - 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; 
    } 


} 
+1

此代碼輸出-1。單元測試在哪裏? – shmosel

+2

熱潮!這在這裏:***如果(名稱==客戶端)*** –

+0

@ΦXocę웃Пepeúpaツ所提供的代碼將不會受到影響。重新打開,直到我們有更多的信息。 – shmosel

回答

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 
} 
0

您必須檢查負值,如果賬戶不存在,也不檢查。您需要添加所有這些驗證以使其正常工作。

相關問題