有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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)

共 (2) 个答案

  1. # 1 楼答案

    根据API文档,如果堆栈是空的,^{}方法将抛出EmptyStackException

    在从堆栈中查看值之前,必须检查堆栈是否为空。有一个^{}方法,它根据堆栈返回布尔值

    Removes the object at the top of this stack and returns that object as the value of this function.

    Returns:

    The object at the top of this stack (the last item of the Vector object).

    Throws:

    EmptyStackException - if this stack is empty.

  2. # 2 楼答案

    一个可能的原因可能是if条件表示if(problem = false){(实际上应该是problem==false或者更好的!problem)。语句problem = false的输出将始终是false,因此每次该条件都会失败,并且不会向Stack添加任何内容(除了开头的s.push(0))。现在,您正试图从Stack中提取(peek())一些内容,而Stack是空的,因此您得到了异常。此外,最好的做法是在从堆栈中取出东西之前,始终检查堆栈是否为空。你可以使用Stack.isEmpty()来达到这个目的。我还没有测试过,但problem = false肯定是错的