java: Trying to return a string value from an array of strings via a method -


public string getvalue(string key) {     (int = 1; i<=length; i++) {         if (key.equals(keyarr[i])) {             return valuearr[i];         }     } } public string getkey(string value) {     string key;     (int = 1; i<=length; i++) {         if (value.equals(valuearr[i])) {             key = keyarr[i];             return key;         }     } } 

i error "this method must return result of type string". 2 arrays valuearr , keyarr both string type arrays. know value of keyarr[i] , valuearr[i] strings because if change return type of method else says expected else , got string.

that's because not return string. e.g. if key not found, if (key.equals(keyarr[i])) { never true , hence, return valuearr[i]; never executed.

to fix this, need following:

  • add return statement after for loop, return something if no match found, e.g.:

    public string getvalue(string key) {     (int = 0; < length; i++) {         if (key.equals(keyarr[i])) {             return valuearr[i];         }     }     return null; } 
  • handle return type in calling method (i.e. add null check or perform appropriate action if no match found).


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -