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);
            }
        }
    }

}

Class Priority Queueを使用して、ノードオブジェクトとして型キャストしようとしていますが、コードに次の例外が表示されます。java.lang.ClassCastException:ノードをjava.lang.comparableにキャストできません。何か案が?優先キューをオブジェクトとして型キャストするのは間違っていますか?前もって感謝します!

4

1 に答える 1

1

Node使用しているクラスがComparable<T>インターフェースを実装していないためにプログラムが失敗していることは、エラーメッセージから非常に明らかです。Comparable<T>インターフェイスPriorityQueueがないと、要素(オブジェクト)の順序付け方法がわかりませんNode

解決:

Nodeクラスを作成してComparableインターフェイスを実装し、public int compareTo(Obj o);をオーバーライドします。いくつかのID/優先度に基づいてノードを比較します(ノードクラスの定義はわかりませんが、x.depthである可能性がありますか?)

public Node implements Comparable<Node> {
   ...
   @Override
   public int compareTo(Node o) {
    return this.priority > o.priority;
   }
}
于 2012-12-08T06:11:08.073 に答える