2011-10-09 44 views
0

所以我的代碼試圖找到一個字符串是否類似於另一個目標字符串(目標已定義)。它根據兩個字符串中有多少個字母相似來得分。然而,在我的for循環中,我得到了用於定義tChar的m的Can not Find Symbol錯誤,但它被用來定義iChar ...我很困惑。有一個更好的方法嗎?錯誤:無法找到循環的符號

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

回答

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

m範圍只在下面的for循環第一條語句,如果你不使用{}。所以,下面的聲明不在循環之內。相反,你需要做 -

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 
} 
+0

我沒想到那個......謝謝! –

0

你需要把護腕放在for循環。目前for循環只是執行iChar線,然後當它退出併到達tChar行時,變量m已超出範圍,因此無法找到。

修復的代碼如下。

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; 
} 
相關問題