Reputation: 51
I try to implement stack structure on Java and I have some problems on the pop method. Before pop, i want to check wether the stack is empty. The return says The local variable item may not have been initialized. When I remove if(!is.empty), it has no error. could someone tell me why? Thanks a lot.
public class ArrayStack {
private String[] s;
private int N=0;
public ArrayStack(){
s=new String[1]; //initialize the array;
}
private void reSize(int capacity){
String[] copy=new String[capacity];
for(int i=0;i<N;i++){
copy[i]=s[i];
}
s=copy;
}
public boolean isEmpty(){
return N==0;
}
public int stackSize(){
return N;
}
public void push(String item){
if(item!=null){
if(N==s.length){
reSize(s.length*2);
}
}
s[N++]=item;
}
public String pop(){
String item;
if(isEmpty()){
item=s[--N];
s[N]=null;
}
if(N>0&&N==s.length/4){
reSize(s.length/4);
}
return item;
}
}
Upvotes: 3
Views: 2869
Reputation: 7495
Option 1, if you want to throws an exception when the stack is empty:
public String pop() {
String item = s[--n];
s[n] = null;
if (n == (s.length / SHRINK_FACTOR)) {
reSize(s.length / SHRINK_FACTOR);
}
return item;
}
Option 2, if you want to return null
when the stack is empty:
public String pop() {
String item = null;
if (!isEmpty()) {
item = s[--n];
s[n] = null;
}
if (n == (s.length / SHRINK_FACTOR)) {
reSize(s.length / SHRINK_FACTOR);
}
return item;
}
Some further notes:
before a variable can be used it must be given an initial value. Therefor if your condition is not met and item
is returned without first giving it a value, the compiler will throw an error.
by convention, class attributes start with a small letter
instead of using magic numbers (4
), introduce some constants in your class:
private static final int SHRINK_FACTOR = 4;
consider writing unit tests to describe and ensure the expected behaviour:
ArrayStackTest.java:
import static org.junit.Assert.*;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;
public class ArrayStackTest {
@Test
public void testPushAndPop() {
final ArrayStack stack = new ArrayStack();
assertTrue(stack.isEmpty());
stack.push("A");
assertFalse(stack.isEmpty());
stack.push("B");
stack.push("C");
assertEquals("C", stack.pop());
assertEquals("B", stack.pop());
assertEquals("A", stack.pop());
}
@Test(expected = Exception.class)
public void testException() {
final ArrayStack stack = new ArrayStack();
stack.pop();
}
// remove @Ignore for option 2
@Ignore
@Test
public void testPopReturnNull() {
final ArrayStack stack = new ArrayStack();
assertNull(stack.pop());
}
}
Upvotes: 1
Reputation: 1850
You haven't initialize your local variable item
String item;
Change it to
String item = ""; or String item = NULL;
should resolve the issue
Upvotes: 0