2013-10-14 7 views
0

Я пишу программу стека в Java. В коде функция push вызывает исключение нулевого указателя. Я предполагаю, что узел не создается. Пожалуйста посоветуй. Заранее спасибоИсключение Nullpointer при создании объекта

//Stack_using_ll is a stack implementation using linked list 
public class Stack_using_ll{ 
    private Node first; 
    private int count; 
    private class Node { 
     private String str; 
     private Node next; 
    }// Node has a value and reference 

    public void push(String item){ 
     Node old_first = first; 
     first = new Node(); 
     first.str = item; 
     first.next = old_first.next; 
     //first = node; 
     count++; 
    }//Inserts a new node 
    public String pop(){ 
     String str_pop = first.str; 
     first = first.next; 
     count--; 
     return str_pop; 
    }//pops the string out of the stack 
    public boolean is_empty(){ 
     if(first == null) 
      return true; 
     else 
      return false; 
    }//check if the stack is empty 

    public static void main(String[] args){ 
     Stack_using_ll stack = new Stack_using_ll() ; 
     stack.push("Jeans"); 
     System.out.println("There are " + stack.count + " elements in stack"); 
    } 
}//End of class Stack_using_ll  

------------- Выход я получаю следующий ------------------- ----------

java.lang.NullPointerException 
    at Stack_using_ll$Node.access$2(Stack_using_ll.java:7) 
    at Stack_using_ll.push(Stack_using_ll.java:14) 
    at Stack_using_ll.main(Stack_using_ll.java:33) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:601) 
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) 
+0

Вы можете использовать LinkedList для этого. – Ingo

ответ

0

В вашей основной метод создания нового объекта Stack_using_ll , это создает любые переменные-члены, однако вы никогда не даете first значение (например, внутри конструктора), поэтому оно остается нулевым.

private Node first; //<--- first is null here and you use the blank constructor, so it is never given a non null value 

Затем вызовите stack.push("Jeans"); в основной метод, который пытается использовать first, но first равно нулю, следовательно, исключение.

public void push(String item){ 
    Node old_first = first; //<-- the initial null is preserved here 
    first = new Node(); 
    first.str = item; 
    first.next = old_first.next; //<-- you attempt to use the preserved null here 
    //first = node; 
    count++; 
} 
+0

@ user2228741 Рад помочь –

0

first равна нулю в начале, так что, когда вы делаете: old_first = first, old_first становится нулевым, поэтому old_first.next дает исключение.

Решение:

public void push(String item){ 
     Node old_first = first; 
     first = new Node(); 
     first.str = item; 
     if(old_first!=null) 
      first.next = old_first.next; 
    ...} 
1

В коде:

public class Stack_using_ll{ 
    private Node first; 

private Node first только объявляет ссылку на узел с именем «первый», он не создает экземпляр узла для него ссылаясь на.

Итак, когда вы позже назначить first к oldFirst, вы назначая null, пытаясь получить доступ к члену нулевых результатов в NPE

public void push(String item){ 
     Node old_first = first; 
     first = new Node(); 
     first.str = item; 
     first.next = old_first.next; <- NPE here 
0

проблемой является нулевым указателем в первый раз вы толкаете к вам объект (потому что первый пункт является недействительным и вы пытаетесь получить его .next

коррекционных ниже: (в нажимной функции)

public void push(String item){ 
    Node old_first = first; 
    first = new Node(); 
    first.str = item; 
    //first time old_first is null! 
    if (old_first != null){ 
     first.next = old_first.next; 
    } 
    //first = node; 
    count++; 
} 
Смежные вопросы