Question: The error is when I test the Peek method in IntelliJ test, it tells Cannot read field data because this.last is null and Unexpected exception


The error is when I test the Peek method in IntelliJ test, it tells Cannot read field "data" because "this.last" is null and Unexpected exception type thrownimport resolve it 

 java.util.EmptyStackException; public class MyStack{   private Node first;   private Node last;   private int   size;   public MyStack(){     first  = null;     last  = null;     size  = 0;   }   public boolean isEmpty(){     return last == null && size == 0;   }   public E peek(){     if(isEmpty()){       throw new EmptyStackException();      }else{     return last.data;}   }   private void detach(){     Node oldLast = last;     last      = last.next;     oldLast.next  = null;   }   public E pop(){     E lastItem = last.data;     detach();     size--;     return lastItem;   }   public E push(E item){     Node oldLast = last;     Node newNode = new Node<>(oldLast, item);     last      = newNode;     if(isEmpty())       first = newNode;     size++;     return item;   }   public int size(){     return size;   }   public String toString(){     if(isEmpty()){       return "[]";     }else{       StringBuilder result = new StringBuilder("[" + last.data);       for(Node node = last.next; node != null; node = node.next)         result.append(", ").append(node.data);       return result + "]";     }   }   static class Node{     E    data;     Node next;     public Node(E data){       this(null,data);     }     public Node(Node next, E data){       this.data = data;       this.next = next;     }   } }

 


Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

The error youre encountering is related to the peek method in your MyStack class The error message C... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!