尽管声明了变量,“找不到符号:变量”

时间:2015-06-26 19:25:44

标签: java

当我编译下面的代码时,它说:

  

“错误:找不到符号:变量max”

但我确实定义了变量max ....

public class Solution {
    public static  boolean isOneEditDistance(String s, String t) {
            if (s.length() >= t.length() ) {
                    StringBuilder a = new StringBuilder (s);
                    StringBuilder b = new StringBuilder (t);
                    int max = s.length();
                    int min = t.length();
            }
            else {
                    StringBuilder a = new StringBuilder (t);
                    StringBuilder b = new StringBuilder (s);
                    int max = t.length();
                    int min = s.length();
            }

            int flag = 0;

            if ( (max-min)>1 )
                    return flase;
            else if ( (max-min)==1 ) {
                .....

4 个答案:

答案 0 :(得分:1)

您的变量/参数范围不正确:

  

如果参数在{}范围内,则范围仅限于这些{}

因此,请将代码更改为此更改范围并解决问题:

public class Solution {
public static  boolean isOneEditDistance(String s, String t) {
int max=0;
int min=0;
        if (s.length() >= t.length() ) {
                StringBuilder a = new StringBuilder (s);
                StringBuilder b = new StringBuilder (t);
                max = s.length();
                min = t.length();
        }
        else {
                StringBuilder a = new StringBuilder (t);
                StringBuilder b = new StringBuilder (s);
                max = t.length();
                min = s.length();
        }

        int flag = 0;

        if ( (max-min)>1 )
                return flase;
        else if ( (max-min)==1 ) {

答案 1 :(得分:1)

我更喜欢下面显示的代码,这也避免了由于a和b在if语句中包含的块中作用域而引起的问题。

 if( s.length() < t.length() ){
     String h = s; s = t; t = h;
 }
 // now s is not shorter than t
 int max = s.length();
 int min = t.length();
 StringBuilder a = new StringBuilder(s);
 StringBuilder b = new StringBuilder(t);

答案 2 :(得分:1)

无法看到变量的原因是由于变量的范围。变量能够“向下钻取”可见性链,但不能“挖掘出来”。由于变量是在if-statemnent中声明的,因此您的变量仅在<{1}}中可见,因为它无法“挖掘出来”。

这是我令人敬畏的MS Paint技能,很难描述我无法“挖掘”范围可见性的意思:

enter image description here

答案 3 :(得分:0)

变量已在if (s.length() >= t.length() )块中初始化。因此,这些变量仅限于此。

解决方案:在条件之前初始化它们。