这个Java代码有什么问题

这个Java代码有什么问题,java,Java,这是我的Josephus类的add方法,其中我应该使用循环链表。我在类中的一些区域中遇到了空指针异常,但这都是因为这个方法。有人能从查看此代码中看到任何明显的错误吗 /** Inserts the specified element in the list at the last position @param dataItem the element to add */ // Complexity O(1) @SuppressWarnings({ "uncheck

这是我的Josephus类的add方法,其中我应该使用循环链表。我在类中的一些区域中遇到了空指针异常,但这都是因为这个方法。有人能从查看此代码中看到任何明显的错误吗

/** Inserts the specified element in the list at the
     last position
     @param dataItem the element to add
   */
 // Complexity O(1)
 @SuppressWarnings({ "unchecked" })
public void add(E dataItem) {
    Node <E> node = new Node <E> (dataItem,null,null);
    if (count == 0){ // list is empty
        head = node.previous= node;  
    }

    else {
       head.previous.next = node;
       node.previous = head.previous;
       head.previous = node;
    }
    count++; 
    }

完整代码:

是的,您需要将else部分用大括号括起来:

public void add(E dataItem) {
    Node <E> node = new Node <E> (dataItem, null, null);
    if (count == 0) { // list is empty
        head = node.previous= node ;  
    } else {
       (head.previous).next = node;
       node.previous = head.previous;
       head.previous = node;
    }
    count++;
}

否则,每次都会执行最后三行,而不仅仅是最后一行。

if/else块周围没有大括号。

有太多未知变量。所以很难看出问题所在。你在else部分使用大括号了吗?最重要的是你在if和else块周围缺少了{}。从链接中发布的代码缩进来看,count++可能不打算包含在else分支的大括号中。@KatjaChristiansen:很好,更新了我的答案。