v变量已初始化

时间:2018-04-03 01:33:13

标签: java initialization

我不理解错误:v variable is been initializedless(k, v),方法中调用方法insert(),因为变量v在上面的行中初始化...但即便如此编译器给了我错误。我的代码是在两个优先级队列中插入一个密钥,我添加了一个我用整数做的测试。

    public class MedianPQ <Key extends Comparable<Key>>{
      private MaxPq left;
      private MinPq right;

      public MedianPQ(int N, int M) {
        left = new MaxPq(N);
        right = new MinPq(M);
      }

      private boolean less( Key k, Key v) {
        return k.compareTo(v) < 0;
      }

      private boolean great( Key k, Key v) {
        return k.compareTo(v) > 0;
      }

      public void insert(Key k) {
        Key v;
        if( left.isEmpty() && right.isEmpty()) v = k; // initial
        else {
          if( less(k, v) && (left.size() < right.size() + 1)) {   //error
            left.insert(k);
          }
          else if( great(k, v) && (right.size() < left.size() + 1)) {
            right.insert(k);
          }
          else {
            if( left.size() == right.size() + 1) {
              right.insert(v);
              left.insert(k);
              v = (Key)left.max();
            }
            else {
              left.insert(v);
              right.insert(k);
              v = (Key)right.min();
            }
          }
        }
      }

测试:

public static void main(String[] args) {
    MedianPQ median = new MedianPQ(100, 100);
    Random rnd = new Random();
    for( int i = 0; i < 20; i++) {
      median.insert(rnd.nextInt(50));
    }

1 个答案:

答案 0 :(得分:1)

v被声明为局部变量,但在重新分配另一个值

之前,您永远不会分配初始值
public void insert(Key k) {
  

Key v = null;

     

或者

     

Key v = new Key();

if( left.isEmpty() && right.isEmpty()) v = k; // initial

else 
{
    if( less(k, v) && (left.size() < right.size() + 1))
    {
        left.insert(k);
    }
    else if( great(k, v) && (right.size() < left.size() + 1)) 
    {
        right.insert(k);
    }
    else 
    {
       if( left.size() == right.size() + 1) 
       {
           right.insert(v);
           left.insert(k);
           v = (Key)left.max();
        }
        else 
        {
           left.insert(v);
           right.insert(k);
           v = (Key)right.min();
        }       
  }