2016-03-26 14 views
1

私は優先度キューを使用したプログラムを試していました。私はプライオリティキューがプライベートにするとき、私はエラーを取得する優先度キューを作成するとJavaでエラーが発生する

KthSmallestPQ.java:8: error: illegal start of expression 
      private PriorityQueue<MatrixElement> queue = new PriorityQueue<MatrixElement>(a[0].length, new Comparator<MatrixElement>() { 
      ^

を言ってコードがコンパイルされ、私がプライベート削除したときに実行されます。誰かがPQをプライベートにするとエラーが発生する理由を説明できますか?ここで

は動作するコードです:あなたはここで作成したqueueあなたがローカルvariable.The変数にaccess specifierを使用することはできません

import java.util.*; 

class KthSmallestPQ { 
    public static int findKthLow(int[][] a, int k) { 
     if(k < 0 || k >= a.length * a[0].length) 
      return Integer.MAX_VALUE; 

     PriorityQueue<MatrixElement> queue = new PriorityQueue<MatrixElement>(a[0].length, new Comparator<MatrixElement>() { 
      public int compare(MatrixElement first, MatrixElement second) { 
       return first.value - second.value; 
      } 
     }); 

     for(int i = 0; i < a[0].length; i++) 
      queue.add(new MatrixElement(a[0][i], 0, i)); 

     MatrixElement lowest = null; 

     for(int i = 0; i < k; i++) { 
      lowest = queue.remove(); 

     // add element from the next row of same column to the priority queue 
      int row = lowest.row + 1; 
      int col = lowest.col; 

      if(row < a.length) 
       queue.add(new MatrixElement(a[row][col], row, col)); 
      else 
       queue.add(new MatrixElement(Integer.MAX_VALUE, row, col)); 
     } 

    return lowest.value; 
} 

    public static void main(String[] args) { 
     int[][] matrix = {{10, 20, 30, 40}, 
       {15, 25, 35, 45}, 
       {24, 29, 37, 48}, 
       {32, 33, 39, 50}}; 

     int k = 6; 
     System.out.println(k + "th smallest value is: " + findKthLow(matrix, k)); 
    } 
} 
class MatrixElement { 
    int value; 
    int row; 
    int col; 

    MatrixElement(int value, int row, int col) { 
     this.value = value; 
     this.col = col; 
     this.row = row; 
    } 
} 
+0

正しいファイルを作成してください(正しく保存してください)。あなたのソースコードに 'プライベート'シンボルがないので。 –

答えて

2

はローカル変数です。

関連する問題