From 9fd420a9af3d5c21a0cfb0010275fe26b2ca87e6 Mon Sep 17 00:00:00 2001 From: Isak Rabin Date: Wed, 31 Oct 2018 14:50:59 +0900 Subject: [PATCH] Add check to avoid null pointer exception --- java/Chapter 3/Question3_3/Question.java | 4 +++- java/Chapter 3/Question3_3/SetOfStacks.java | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/java/Chapter 3/Question3_3/Question.java b/java/Chapter 3/Question3_3/Question.java index 18acfe5d..5ae3b602 100644 --- a/java/Chapter 3/Question3_3/Question.java +++ b/java/Chapter 3/Question3_3/Question.java @@ -8,7 +8,9 @@ public static void main(String[] args) { set.push(i); } for (int i = 0; i < 34; i++) { - System.out.println("Popped " + set.pop()); + if (!set.isEmpty()) { + System.out.println("Popped " + set.pop()); + } } } } diff --git a/java/Chapter 3/Question3_3/SetOfStacks.java b/java/Chapter 3/Question3_3/SetOfStacks.java index 8e3cc0e0..fda9c8cc 100644 --- a/java/Chapter 3/Question3_3/SetOfStacks.java +++ b/java/Chapter 3/Question3_3/SetOfStacks.java @@ -30,6 +30,9 @@ public void push(int v) { public int pop() { Stack last = getLastStack(); + if (last==null){ + throw new Exception("Stack is empty - No more element is available"); + } int v = last.pop(); if (last.size == 0) { stacks.remove(stacks.size() - 1);