java上的EmptyStackException
当我运行下面的源代码时
import java.util.Stack;
public class Assignment3 {
boolean conflict, complete = false;
public static int solve(int n) {
int solution = 0;
int nextQueen = 0;
boolean problem = false;
s.push(0);
do{
for(int i = 0; i < s.size(); i++)
{
if(s.get(i) == nextQueen){
problem = true;
break;
}
else if(s.get(i) - i == nextQueen - s.size()){
problem = true;
break;
}
else if(s.get(i) + i == nextQueen + s.size()){
problem = true;
break;
}
}
if(problem = false){
s.push(nextQueen);
nextQueen = 0;}
else{
nextQueen++;
}
if(nextQueen == n){
if(s.peek() == n){
s.pop();
nextQueen = s.pop()+ 1;
}
else{
nextQueen = s.pop()+ 1;
}
}
}while(s.size() != n);
printSolution(s);
solution++;
return solution;
}
private static void printSolution(Stack<Integer> s) {
for (int i = 0; i < s.size(); i ++) {
for (int j = 0; j < s.size(); j ++) {
if (j == s.get(i))
System.out.print("Q ");
else
System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
// ----- the main method -----
// (you shouldn't need to change this method)
public static void main(String[] args) {
int n = 8;
// pass in parameter n from command line
if (args.length == 1) {
n = Integer.parseInt(args[0].trim());
if (n < 1) {
System.out.println("Incorrect parameter");
System.exit(-1);
}//if
}//if
int number = solve(n);
System.out.println("There are " + number + " solutions to the " + n + "-queens problem.");
}
}
获取以下错误。请帮助我清除:
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:79)
at Assignment3.solve(Assignment3.java:40)
at Assignment3.main(Assignment3.java:87)
# 1 楼答案
根据API文档,如果堆栈是空的,^{} 方法将抛出
EmptyStackException
在从堆栈中查看值之前,必须检查堆栈是否为空。有一个^{} 方法,它根据堆栈返回布尔值
# 2 楼答案
一个可能的原因可能是if条件表示
if(problem = false){
(实际上应该是problem==false
或者更好的!problem
)。语句problem = false
的输出将始终是false
,因此每次该条件都会失败,并且不会向Stack
添加任何内容(除了开头的s.push(0)
)。现在,您正试图从Stack
中提取(peek()
)一些内容,而Stack
是空的,因此您得到了异常。此外,最好的做法是在从堆栈中取出东西之前,始终检查堆栈是否为空。你可以使用Stack.isEmpty()
来达到这个目的。我还没有测试过,但problem = false
肯定是错的