这是我的代码。它应该接受两个字符串并逐字符地比较它们的差异。
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.
答案 0 :(得分:7)
您的length
变量在if
和else
的每种情况下都被声明和初始化,然后在块结束时立即被丢弃,超出范围。
在if
之前声明它并在每种情况下初始化它,因此它仍然在for
循环的范围内进一步向下。
int length;
if(first.length()>second.length()){
length = first.length();
}else{
length = second.length();
}