2015-04-01 71 views
0

我似乎不明白为什么java不会允许我在while循环下的solve方法中有else if语句,它告诉我这是一个语法错误。我认为在else if语句之后的条件是正确的语法,但它不适用于我。为什么不会让java让我有这个else语句?

//Class to solve simple N Queens problem with backtracking, but without using recursion in a 1-d array. 
    public class NQueens 
    { 
     private int N; 
     private int board[]; 
     public NQueens(int n) 
     { 
      this.N = n; 
      this.board = new int[N]; 
      for(int i = 0; i<N; i++) 
      { 
       this.board[i]=-1; 
      } 
     } 
     //checks the place for any attack queens in the same column, or diagnol 
     public boolean safePlace(int row, int col, int [] board) 
     { 
      for (int i = 0; i<row; i++) 
      { 
       if((board[i] == col)|| (i-row)==(board[i]-col)|| (i-row)==(col-board[i])) 
        return false; 
      } 
      return true; 
     } 
     //solves N Queens problem using backtracking 
     public void solve() 
     { 
      int row=0; 
      while(row<this.N && row>-1) 
      { // condition that the row is empty and the queen is safe to place 
       int col=0; 
       if(this.board[row]==-1 && safePlace(row, col, this.board)); 
       { 
        this.board[row]=col; 
        row++; 
       } 
       //condition that the row is not empty 
       else if(this.board[row]>-1) 
       { 
        //start at column after the previous queen's column position. 
        col=this.board[row-1]+1; 
        //checks for safety 
        if(safePlace(row, col, this.board)) 
        { 
         this.board[row]=col; 
        } 
       } 
       else //condition that no safe column can be found so queen in row is removed and we move back one row 
       { 
        this.board[row]=-1; 
        row--; 
       } 
      } 
      printBoard(); 
     } 

     public void printBoard() 
     { 
       System.out.println("got to solve loop"); 
       for(int i = 0; i<N; i++) 
       { 
        int chessBoard[]=new int[N]; 
        chessBoard[this.board[i]] = 1; 

        if(chessBoard[i]==0) 
         System.out.print("* "); 
        else 
         System.out.print("Q "); 

       } 
     } 

     public static void main(String[] args) 
     { 
      NQueens q = new NQueens(4); 
      q.solve(); 

     } 
    } 

回答

3

你必须在if声明分号,必须将其删除:

// semi-colon acts as an empty statement 
if(this.board[row]==-1 && safePlace(row, col, this.board)); 
0

第一if语句后删除分号,你应该是好去!

1

删除分号

if(this.board[row]==-1 && safePlace(row, col, this.board)); 

semiolon用来结束语句所以else部分会说,没有if它给你的错误。

+0

哦,我的上帝,我现在觉得这么愚蠢,那是我的代码,直到凌晨4点才开始编码......谢谢singkakash,这对我来说是一个愚蠢的错误。 – spstephens 2015-04-01 16:57:31

+0

@spstephens你的欢迎 – silentprogrammer 2015-04-01 16:58:36

相关问题