0

For one of my classes we just began using IntLinkedStacks, and I need to add a size() method that will count the size of my list. So, I began by creating an instance variable to define size, and then began coding. However, in my program, I keep getting a Null Exception Error. I read up what this error means, but could someone clarify what it means within this code, and why I am getting this error?

import java.util.EmptyStackException;

public class IntLinkedStack implements IntStack {
   private Node top;
   private int size;

   public void push(int item) {
      top = new Node(item, top);
   }

   public int pop() {
      if (isEmpty()) {
         throw new EmptyStackException();
      }
      int value = top.data;
      top = top.next;
      return value;
   }

   public boolean isEmpty() {
      return top == null;
      // return (size() == 0);
   }

   public int peek() {
      if (isEmpty()) {
         throw new EmptyStackException();
      }
      return top.data;
   }

   public int size() {
      for(Node n = top; n.next != null; n = n.next)
       size ++;
      return size;
   }

   private static class Node {
      private int data;
      private Node next;

      private Node(int data, Node next) {
         this.data = data;
         this.next = next;
      }
   }

   public static void main(String[] args) {
      IntStack s = new IntLinkedStack();
      System.out.println("Size: " + s.size());
      for (int i = 0; i < 5; i++) {
         s.push(i*i);
      }
      System.out.println("Size: " + s.size());
      while (!s.isEmpty()) {
         System.out.print(s.pop() + " ");
      }
      System.out.println();
      System.out.println("Size: " + s.size());
   }

}
Coding Noob
  • 23
  • 1
  • 5
  • First, identify *where* the exception occurs--you're getting a clear error message with a specific line number. Then look at the line and figure out what could equal null. Note: What happens to your `for` condition when your stack is completely empty? – chrylis -cautiouslyoptimistic- Oct 03 '16 at 00:02
  • Great! So I changed my for loop to the following : for(Node n = top; top != null; n = n.next) Now I am receiving a value for size, which is equals zero after running the program, but I am still receiving the same error. – Coding Noob Oct 03 '16 at 00:08
  • Write out the logic for your `size()` method on paper. As a hint, it may be simplest to special-case the empty list. – chrylis -cautiouslyoptimistic- Oct 03 '16 at 01:03
  • @chrylis Thanks! I simply just added another class stating that size = 0; with an instance variable private int size;. I then added size++ to my push class, and size-- to my pop class. Then just returned size for my size method. – Coding Noob Oct 03 '16 at 01:24

0 Answers0