-1

When I compile the code below, I get an error:

"cannot find symbol - variable wayA"

Can someone please explain the reason?

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??
    } 
Gal Yakir
  • 135
  • 1
  • 10
  • 4
    `wayA` is defined inside an `if` block and is not visible outside of it. – Phylogenesis Sep 04 '17 at 16:15
  • @GalYakir please accept an answer, we spend time to answer you properly you can take 10sec to accept ;) – azro Sep 05 '17 at 16:49
  • Please think about accept an answer, this is how a forum works, and a new user would be more attracted from accepted post than non-accepted post – azro May 12 '18 at 12:20

2 Answers2

6

The variable wayA is defined in the scope of the if block, so it does exists only between the brackets of the if , so you can't have access to it later

if(len2>len1){
   int wayA = 1 + edit(str1+str2.charAt(0),str2.substring(0),i,j);
}
return Math.min(wayD,wayA);

You need to define it before :

int wayA = 0;
if(len2>len1){
   wayA = 1 + edit(str1+str2.charAt(0),str2.substring(0),i,j);
}
return Math.min(wayD,wayA);
azro
  • 53,056
  • 7
  • 34
  • 70
1

Compiler cant find wayA because you declared it in the if block. Move the declaration of your int wayA out of that if block. Like this:

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);
Tom Stein
  • 345
  • 2
  • 15