为什么java不让我使用这个else if语句?
我似乎不明白为什么java不允许我在while循环下的solve方法中使用else if语句,它告诉我这是一个语法错误。我认为在else-if语句之后加上一个条件,这将是正确的语法,但它对我不起作用为什么java不让我使用这个else if语句?,java,if-statement,Java,If Statement,我似乎不明白为什么java不允许我在while循环下的solve方法中使用else if语句,它告诉我这是一个语法错误。我认为在else-if语句之后加上一个条件,这将是正确的语法,但它对我不起作用 //Class to solve simple N Queens problem with backtracking, but without using recursion in a 1-d array. public class NQueens { privat
//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();
}
}
//类通过回溯解决简单的N皇后问题,但不在一维数组中使用递归。
公开课
{
私人int N;
私人国际董事会[];
公共图书馆(国际北)
{
这个,N=N;
this.board=新整数[N];
对于(int i=0;i您在if
语句中有一个分号,必须删除该分号:
// semi-colon acts as an empty statement
if(this.board[row]==-1 && safePlace(row, col, this.board));
if
语句中有分号,必须删除该分号:
// semi-colon acts as an empty statement
if(this.board[row]==-1 && safePlace(row, col, this.board));
删除第一个if语句后的分号,您就可以开始了!删除第一个if语句后的分号,您就可以开始了!删除分号
if(this.board[row]==-1 && safePlace(row, col, this.board));
分号用于结束语句,因此else
部分会说没有if
会导致错误。删除分号
if(this.board[row]==-1 && safePlace(row, col, this.board));
semiolon用于结束语句,因此else
部分会说没有if
会给您带来错误。哦,我的天啊,我现在觉得自己太愚蠢了,这就是我一直到凌晨4点才开始编码的原因……感谢singkakash,这对我来说是一个愚蠢的错误。@spstephens您的福祉哦,我的天啊,我现在觉得自己太愚蠢了,以至于这就是我凌晨4点才开始编码的原因……谢谢你辛卡卡什,我犯了一个愚蠢的错误。@spstephens欢迎你