Home > database >  Return string of first character if it contains more than 4 characters, otherwise return the last ch
Return string of first character if it contains more than 4 characters, otherwise return the last ch

Time:05-11

The question is: Given a string return the first character in the string if it contains more than 4 characters, and the last character otherwise. Example out comes below

firstOrLastChar("kwk") -> 'k'
firstOrLastChar("gals") -> 's'
firstOrLastChar("uocrws") -> 'u'

This is the code I've gotten done, but it returns a char not a string so i get this type of error of it being incompatible types. really lost on how to go about it

  if (str.length() > 4)
        return str.charAt(0);
    return str.charAt(str.length() - 1);

CodePudding user response:

If I understand your question, it looks like you want to return a String type instead of char type, then you can do following :

if (str.length() > 4)
        return String.valueOf(str.charAt(0));
    return String.valueOf(str.charAt(str.length() - 1));

CodePudding user response:

Try to return it by using .toString() at the end, like this:

if (str.length() > 4) {
        return str.charAt(0);
    }
return str.charAt(str.length() - 1).toString();
  •  Tags:  
  • java
  • Related