如果在外部使用,则在内部使用变量

olhwl3o2  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(250)

这个问题在这里已经有答案了

使用if语句中定义的变量[重复](6个答案)
5年前关门了。
我想得到的是字符串a的第一个字符,和字符串b的最后一个字符。空a应返回“@+lastb”,空b应返回“firsta+@”。
示例:a=“hello”,b=“hi”应返回“hi”;a=“”和b=“hi”返回“@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;
}

我得到的错误信息是变量无法解析,我猜这意味着它们从未被生成?

baubqpgj

baubqpgj1#

必须在条件之前声明变量,以便它们在条件之后保留在作用域中。

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

相关问题