“找不到符号:变速”尽管声明变量

当我编译下面的代码,它说:“找不到符号:变速”尽管声明变量

"error: cannot find symbol: variable max"

但我没有定义变量max ....

public class Solution { 

public static boolean isOneEditDistance(String s, String t) {

if (s.length() >= t.length()) {

StringBuilder a = new StringBuilder (s);

StringBuilder b = new StringBuilder (t);

int max = s.length();

int min = t.length();

}

else {

StringBuilder a = new StringBuilder (t);

StringBuilder b = new StringBuilder (s);

int max = t.length();

int min = s.length();

}

int flag = 0;

if ((max-min)>1)

return flase;

else if ((max-min)==1) {

.....

回答:

我宁愿如下所示的代码,这也避免了因和问题B是作用域包含在if语句块。

if(s.length() < t.length()){ 

String h = s; s = t; t = h;

}

// now s is not shorter than t

int max = s.length();

int min = t.length();

StringBuilder a = new StringBuilder(s);

StringBuilder b = new StringBuilder(t);

回答:

你变量/参数的范围不正确:

If a parameter is within { } the scope is limited to within these { }

因此,将您的代码更改为此以更改范围并解决问题:

public class Solution { 

public static boolean isOneEditDistance(String s, String t) {

int max=0;

int min=0;

if (s.length() >= t.length()) {

StringBuilder a = new StringBuilder (s);

StringBuilder b = new StringBuilder (t);

max = s.length();

min = t.length();

}

else {

StringBuilder a = new StringBuilder (t);

StringBuilder b = new StringBuilder (s);

max = t.length();

min = s.length();

}

int flag = 0;

if ((max-min)>1)

return flase;

else if ((max-min)==1) {

回答:

变量不能被看到的原因是由于变量的范围。变量能够“钻取”可见性链,但不能“挖掘”。由于该变量是在if-statemnent中声明的,因此您的变量仅在之间可见,因为它不能“挖出”。

这里是我真棒MS画图技能较差描绘我的意思大约未能范围能见度“挖出”:

回答:

变量已经在if (s.length() >= t.length())块被初始化。因此这些变量仅限于它。

解决方案:在条件之前初始化它们。

以上是 “找不到符号:变速”尽管声明变量 的全部内容, 来源链接: utcz.com/qa/260184.html

回到顶部