Closed. This question is not reproducible or was caused by typos。它当前不接受答案。
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
5年前关闭。
我似乎不明白为什么Java不允许我在while循环下的resolve方法中使用else if语句,它告诉我这是一个语法错误。我认为在else if语句后加一个条件,这将是正确的语法,但对我不起作用。
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
5年前关闭。
我似乎不明白为什么Java不允许我在while循环下的resolve方法中使用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
{
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();
}
}
最佳答案
if
语句中有分号,必须将其删除:
// semi-colon acts as an empty statement
if(this.board[row]==-1 && safePlace(row, col, this.board));
关于java - 为什么Java不会让我拥有其他if语句? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29396462/
10-13 22:59