java.lang.NullPointerException错误,如何修复?

时间:2015-01-21 04:13:00

标签: java runtime-error

当我从主程序运行程序时,我收到此行的错误: 私有类Node

我有一个(循环)链表列表,其中包含一堆方法(这里只显示第一个),然后是一个单独的main。 我想知道造成这个问题的原因。任何帮助将不胜感激。谢谢。

    public class CircleGame 
    {
        //Node class (inner class)
        private class Node
        {
            private int data;
            private Node next;

            //constructor of Node
            private Node(int data, Node next)
            {
                this.data = data;
                this.next = next;

            }
        }

        /****************************************************/

        private Node head;
        int size =0;
        int k = 0;
        int s = 0;

        //constructor of list
        public CircleGame()
        {
            head = null;

        }

        /****************************************************/

        public void addToEnd(int data)
        {
            //insert at beginning
            if (head == null)
                head = new Node(data, null);

            //insert at other positions
            else 
            { Node temp = head;
                int i=0;
                while(i <size)
                { 
                    temp = temp.next;
                    temp.next = new Node(data, head); 

                    i++;
                }
            }

            size ++;
        }

        /**************************************************/

    //main 
   import java.util.*;

public class CircleGameMain
{
    public static void main (String [] args)
    {
        Scanner keyboard = new Scanner(System.in);
        CircleGame game = new CircleGame();

        System.out.println("***********WELCOME TO The CIRCLE GAME************");
        System.out.print("How many players are in the circle? ");
        int size = keyboard.nextInt();
        System.out.println();
        int data;

        for(int i = 0; i < size; i++) 
        {
            data = i+1;
            game.addToEnd(data);
        }

        game.print();
        System.out.print("What position would you like to start at? ");
        int s = keyboard.nextInt();
        System.out.println();

        System.out.print("Eliminate the kth player. k= ? ");
        int k =keyboard.nextInt();
        System.out.println();
        game.game(s,k);

    }
}

1 个答案:

答案 0 :(得分:1)

我可以发现的一个错误是以下行:

temp.next = new Node(data, head);

应该在while循环之后执行 - 不在其中!