开发者

java: variable not known in current context?

This line is generating a 'not known in current context' compiler error. Why?

if (inputMatrix[newPosition.i][newPosition.j]=='*'){
        // variable not known in current context, why? 
        }

Method declaration:

 static Point moveForward(Point oldPosition, int matrixSize, char orientation, char [][] inputMatrix){

         // add possible new Position
        Point newPosition;

        //first return oldPosition border positions in which the robot shouldn't move 

        if ((orientation=='O')&&(oldPosition.j==0))
               return oldPosition;

        if ((orientation=='E')&a开发者_如何学Cmp;&(oldPosition.j==(matrixSize-1)))
               return oldPosition;

         if ((orientation=='N')&&(oldPosition.i==0))
               return oldPosition;

         if ((orientation=='S')&&(oldPosition.i==(matrixSize-1)))
               return oldPosition;


         if ((orientation=='O'))
             newPosition = new Point(oldPosition.i, oldPosition.j-1);
         if ((orientation=='E'))
             newPosition = new Point(oldPosition.i, oldPosition.j+1);
        if ((orientation=='S'))
             newPosition = new Point(oldPosition.i-1, oldPosition.j);
        if ((orientation=='N'))
             newPosition = new Point(oldPosition.i+1, oldPosition.j);


        //then return oldPosition for positions in which the robot is blocked by *
        if (inputMatrix[newPosition.i][newPosition.j]=='*'){
        // variable not known in current context, why? 
        }




        return null;


    }


Because it is not guaranteed that newPosition has been initialized. Use

Point newPosition = null;

at the beginning of the file. This will initialize the variable value with null at least.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜