当我编译下面的代码时,我收到一个错误:
“找不到符号 - 变量wayA”
有人可以解释原因吗?
private static int edit (String str1, String str2,int i, int j)
{
int len1=str1.length();
int len2 = str2.length();
if(len1==0 || len2==0)
return 0;
if(str1.charAt(0)==str2.charAt(0))
return edit(str1.substring(1),str2.substring(1),i,j);
int wayD =1+ edit
(str1.substring(1),str2,i,j);
if(len2>len1)
{
int wayA = 1+edit(str1+str2.charAt(0),str2.substring(0),i,j);
}
return Math.min(wayD,wayA);
// when i compile "cannot find symbol - variable wayA" why??
}
答案 0 :(得分:6)
变量wayA
在scope
块的if
中定义,因此if
的括号之间仅存在 ,以便您以后无法访问
if(len2>len1){
int wayA = 1 + edit(str1+str2.charAt(0),str2.substring(0),i,j);
}
return Math.min(wayD,wayA);
您需要在之前定义:
int wayA = 0;
if(len2>len1){
wayA = 1 + edit(str1+str2.charAt(0),str2.substring(0),i,j);
}
return Math.min(wayD,wayA);
答案 1 :(得分:1)
编译器无法找到wayA因为你在if块中声明了它。将int wayA的声明移出if块。像这样:
private static int edit (String str1, String str2,int i, int j)
{
int len1=str1.length();
int len2 = str2.length();
if(len1==0 || len2==0)
return 0;
if(str1.charAt(0)==str2.charAt(0))
return edit(str1.substring(1),str2.substring(1),i,j);
int wayD = 1 + edit(str1.substring(1),str2,i,j);
int wayA = 0;
if(len2>len1)
{
wayA = 1+edit(str1+str2.charAt(0),str2.substring(0),i,j);
}
return Math.min(wayD,wayA);