2012-12-08 124 views
0
public LightsOutBFS(){ 
    //readtext 
    int[] arr = new int[25]; 
    int[] state = new int[25]; 
    int[] soln = new int[25]; 

    boolean check=true; 
    PriorityQueue<Node> q = new PriorityQueue<Node>(); 

    //Reading the text file 
    try{ 
     FileInputStream fstream = new FileInputStream("switches.txt"); 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String strLine; 
     int i = 0; 

     //Read File Line By Line 
     while ((strLine = br.readLine()) != null) { 
       //tokenize strline 
       StringTokenizer st = new StringTokenizer(strLine, " \n"); 
       while(st.hasMoreTokens()) { 
       arr[i]=Integer.parseInt(st.nextToken()); 
       i++; 
      } 
     //Close the input stream 
     }in.close(); 


    }catch (Exception e){//Catch exception if any 
     System.err.println("Error: " + e.getMessage()); 
    } 
    for(int i=0; i<25; i++){ 
     state[i]=0; 
     soln[i]=0; 
    } 
    //loop that flips the adjacent side of switches turned on 
    for(int i=0;i<25;i++){ 
     if(arr[i]==1) 
      method.flip_adjacent(i,state); 
    } 


    //implement bfs here 
    parent = new Node(state,0,soln,null); 


    q.offer(parent); 
    while(check){ 
     while(!q.isEmpty()){ 
      Node x = q.poll(); 
      int depth = x.depth; 
      int posMoves = 25-depth; 
      for(int i=0; i<posMoves;i++){ 
       current = generateNode(x.state,depth,x.soln,x); 
       if(EtoNaYun(current.state)) 
        check=false;//check state; 
       q.offer(current); 
      } 
     } 
    } 

} 

我想使用類優先級隊列和類型轉換爲節點對象,但我的代碼顯示此異常:java.lang.ClassCastException:節點不能轉換爲java.lang.comparable。任何想法?將類型優先隊列作爲對象是否錯誤?提前致謝!Java優先隊列錯誤

+0

哪條線給出錯誤? – gsingh2011

+0

它沒有明確說明哪一行有錯誤,它只是打印ClassCastException – user1711194

回答

1

從錯誤消息中可以明顯看出,由於您正在使用的Node類沒有實現Comparable<T>接口,所以程序失敗。如果沒有Comparable<T>接口PriorityQueue將不知道如何訂購元素(Node對象)。

解決方案:

讓您的節點的類來實現Comparable接口和覆蓋公衆詮釋的compareTo(的OBJ O); (我不知道你的Node類的定義,但可能是x.depth?)

public Node implements Comparable<Node> { 
    ... 
    @Override 
    public int compareTo(Node o) { 
    return this.priority > o.priority; 
    } 
}