2014-09-26 48 views
0

這是我的代碼。它應該採取兩個字符串,並逐字比較它們的差異。爲什麼在嘗試使用局部變量時出現「找不到符號」錯誤?

import java.util.Scanner; 
public class Positions { 
public static void main(String[] args){ 
    Scanner scan = new Scanner(System.in); 
    String first = scan.next(); 
    String second = scan.next(); 
    if(first.length()>second.length()){ 
    int length = first.length(); 
    }else{ 
    int length = second.length(); 
    } 
    for(int i=0; i<length; i++){ 
    if(first.charAt(i)!=second.charAt(i)){ 
     System.out.print(i+" "+first.charAt(i)+" "+second.charAt(i)); 
    } 
    } 
} 
} 

,當我嘗試編譯我收到此錯誤:

----jGRASP exec: javac -g Positions.java 
Positions.java:12: error: cannot find symbol 
     for(int i=0; i < length; i++){ 
        ^
    symbol: variable length 
    location: class Positions 
1 error 

----jGRASP wedge: exit code for process is 1. 
----jGRASP: operation complete. 
+2

Google「可變範圍」。 – Pshemo 2014-09-26 23:01:21

+0

http://stackoverflow.com/questions/25706216/what-does-a-cannot-find-symbol-compilation-error-mean的候選副本 – 2014-09-26 23:11:06

回答

7

length變量聲明,並在ifelse每種情況下初始化,然後立即丟棄超出範圍時,該塊結束。

if之前聲明並在每種情況下對其進行初始化,因此它將繼續保留在for循環的範圍內。

int length; 
if(first.length()>second.length()){ 
    length = first.length(); 
}else{ 
    length = second.length(); 
} 
相關問題