Java:在while循环中定义的String []的"找不到符号"错误

Dav*_*vid 1 java symbols while-loop

这是相关的代码:

public static String[] runTeams (String CPUcolor) 
{  
    boolean z = false ; 
    //String[] a = new String[6] ; 
    boolean CPU = false ; 
    while (z == false) 
    { 
        while (CPU==false) 
        {
            String[] a = assignTeams () ; 
            printOrder (a) ;

            for (int i = 1; i<a.length; i++) 
            { 
                if (a[i].equals(CPUcolor)) CPU = true ;
            }
            if (CPU==false) 
            {
                System.out.println ("ERROR YOU NEED TO INCLUDE THE COLOR OF THE CPU IN THE TURN ORDER") ; 
            }
        }
        System.out.println ("is this turn order correct? (Y/N)") ; 
        String s = getIns () ; 
        while (!((s.equals ("y")) || (s.equals ("Y")) || (s.equals ("n")) || (s.equals ("N")))) 
        {
            System.out.println ("try again") ; 
            s = getIns () ; 
        } 
        if (s.equals ("y") || s.equals ("Y") ) 
        z = true ; 
    } 
    return a ; 
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

Risk.java:416: cannot find symbol
symbol  : variable a
location: class Risk
        return a ; 
               ^
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此错误?似乎aString[] a = assignTeams () ; and if anything is used by the lineprintOrder(a)行中有明确的定义;`在我看来,如果真的找不到符号,那么编译器应该在那里爆炸,而不是在返回语句中.

(也是方法assignTeams返回一个字符串数组.)

Kal*_*see 7

变量a是在while (CPU==false)循环范围内定义的- 它不能在while循环范围之外访问.您需要a在最外层范围内定义(与return语句所在的范围相同).您可以将分配保留在原来的位置,或者如果可能的话,可以在定义的同时进行分配.

public static String[] runTeams (String CPUcolor) 
{  
    boolean z = false ; 
    String[] a = null; // define a here, assign to null value
    boolean CPU = false ; 
    while (z == false) 
    { 
        while (CPU==false) 
        {
            a = assignTeams () ; // assign a here
            printOrder (a) ;

            for (int i = 1; i<a.length; i++) 
            { 
                if (a[i].equals(CPUcolor)) CPU = true ;
            }
            if (CPU==false) 
            {
                System.out.println ("ERROR YOU NEED TO INCLUDE THE COLOR OF THE CPU IN THE TURN ORDER") ; 
            }
        }
        System.out.println ("is this turn order correct? (Y/N)") ; 
        String s = getIns () ; 
        while (!((s.equals ("y")) || (s.equals ("Y")) || (s.equals ("n")) || (s.equals ("N")))) 
        {
            System.out.println ("try again") ; 
            s = getIns () ; 
        } 
        if (s.equals ("y") || s.equals ("Y") ) 
        z = true ; 
    } 
    return a ; 
}
Run Code Online (Sandbox Code Playgroud)