Rachel Swinehart
Rachel Swinehart

Reputation: 1

Error: Cannot Find Symbol from for loop

So my code is trying to find if a string is similar to another target string (target already defined). It makes a score based on how many letters are similar in both strings. However, in my for loop, I get a Cannot Find Symbol error for the m used in defining tChar, but it's been used to define iChar... I'm so confused. Is there a better way to do this?

public int score(String input){
    int score;
    char iChar, tChar;
    for (int m=0;m<input.length();++m)
        iChar = input.charAt(m);
        tChar = target.charAt(m);
        if (iChar == tChar)
            score = score + 1;
        else
            score = score;
    return score;
}

Upvotes: 0

Views: 1961

Answers (2)

lynks
lynks

Reputation: 5689

You need to put bracers around your for loop. At the moment the for loop is just executing the iChar line over and over, then when it exits and gets to the tChar line, the variable m is out of scope and so cannot be found.

The repaired code is below.

public int score(String input) {
    int score = 0; //i know java instantiates variables for you, but if you do it explicitly, it serves to document your code.
    char iChar, tChar;
    for (int m = 0; m < input.length(); m++) {
        iChar = input.charAt(m);
        tChar = target.charAt(m);
        if (iChar == tChar) score++; //abbreviated and else clause removed, as it was doing nothing.
    }
    return score;
}

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

for (int m=0;m<input.length();++m) 
    iChar = input.charAt(m);  // Only this statement come under loop.

The scope of m is only with in first statement following the for loop, if you are not using {}. So, the following statement(s) there after doesn't come under for loop. Instead you need to do -

for (int m=0;m<input.length();++m)  // Now m is block scoped
{
        iChar = input.charAt(m);
        tChar = target.charAt(m);
        if (iChar == tChar)
            score = score + 1;
        else
            score = score;   // I don't see any use of else at all
}

Upvotes: 1

Related Questions