为什么忽略我的break语句?

时间:2015-02-03 03:29:47

标签: java

在if语句下的方法中:

if (currentLocationX == 0 && currentLocationY == 4)

我有一个break语句,应该让程序退出while循环并返回true以回答'并为方法。然而经过一些测试后,似乎在返回true后回复'它会回到while循环中,最后给出错误的结果。为什么我的休息声明没有做到它应该做的事情?谢谢! 附: (这种方法调用了其他一些与此处无关的方法)

public  boolean solveMaze()
      {
          boolean answer = false;

          int currentLocationX;
          int currentLocationY;
          //push starting location

          pushX(2);
          pushY(1);

          while((isEmptyX() == false) && (isEmptyY() == false))
          {
              printMaze();
              System.out.println();
              currentLocationX = popX();
              currentLocationY = popY();

            //mark current location as visited
               visited(currentLocationX, currentLocationY, maze);
               System.out.println("Current Location: " + currentLocationX + ", " + currentLocationY);

              if (currentLocationX == 0 && currentLocationY == 4)

              {

                  answer = true;
                  break;
              }



             else
               {
                //push all unvisited OPEN neighbor locations into stack
                if (checkEast(currentLocationX, currentLocationY) == 0)
                {
                  pushX(eastX(currentLocationX));
                  pushY(eastY(currentLocationY));
                }

                else;

                if (checkSouth(currentLocationX, currentLocationY)== 0)
                {
                  pushX(southX(currentLocationX));
                  pushY(southY(currentLocationY));
                }
                else;
                if (checkWest(currentLocationX, currentLocationY)== 0)
                {
                  pushX(westX(currentLocationX));
                  pushY(westY(currentLocationY));
                }
                else;
                if (checkNorth(currentLocationX, currentLocationY)== 0)
                {
                  pushX (northX(currentLocationX));
                  pushY(northY(currentLocationY));
                }
                else;     
                }

            }

              return answer;

      }

1 个答案:

答案 0 :(得分:0)

我把你方法的基本逻辑写成

public static boolean solveMaze() {

    boolean answer = false;
    int currentLocationX = 0;
    int currentLocationY = 4;

    while (true) {
        if (currentLocationX == 0 && currentLocationY == 4) {
            System.out.println("Hit the break");
            break;
        } else {
            System.out.println("Missed the break");
        }
    }

    return answer;
}

如果你执行它,你会得到Hit the break。所以,一旦满足你的if语句,你的solveMaze()方法就可以突破循环。我会说,如果你看到你的代码随后回到while循环,那么必须是第二次调用solveMaze()