0

What i'm trying to to is to get the first char of string a, and last char of string b. Empty a should return "@+lastb" and empty b should return "firsta+@".

examples: a = "hello", b = "hi" should return "hi"; a = "" and b = "hi" returns "@i";

public String lastChars(String a, String b) {
 if(a.length() > 0) {
   String firstA = a.substring(0,1);
 }
 else {
   String firstA = "@";
 }
 if(b.length() > 0) {
   String lastB = b.substring(b.length()-1);
 }
 else {
   String lastB = "@";
 }
 return firstA + lastB;
}

the error message i get is that the variables cannot be resolved, which im guessing means that they never were made?

kensil
  • 126
  • 1
  • 6
  • 15
  • You're declaring the variables inside blocks, they won't be known in the `return` statement. – Maroun Jan 15 '15 at 11:08
  • This is java not javascript, you cant do that. Everything in java is block-level scoped. – Biu Jan 15 '15 at 11:10

1 Answers1

1

You must declare the variables before the conditions, in order for them to remain in scope after the conditions.

public String lastChars(String a, String b) 
{
    String firstA = "";
    String lastB = "";
    if(a.length() > 0) {
        firstA = a.substring(0,1);
    } else {
        firstA = "@";
    }
    if(b.length() > 0) {
        lastB = b.substring(b.length()-1);
    } else {
        lastB = "@";
    }
    return firstA + lastB;
}
Eran
  • 387,369
  • 54
  • 702
  • 768