程序是这样的,是哪里有问题导致运行出错:java.lang.nullpointerexception.谢谢先~
class StackOfInteger
{
private int[] element;
private int size;
public StackOfInteger()
{
this(16);
}
public StackOfInteger(int capacity)
{
int[] element=new int[capacity];
}
public boolean empty()
{
if(size==0)
return true;
else
return false;
}
public int peek()
{
return element[size-1];
}
public void push(int value)
{
if(size>=16)
{
int[] temp=new int[element.length*2];
System.arraycopy(element,0,temp,0,element.length);
element=temp;
}
element[size++]=value;
}
public int pop()
{
return element[--size];
}
public int[] getElement()
{
return element;
}
}
class Exercise10_5b
{
public static void main(String[] args)
{
StackOfInteger stack=new StackOfInteger();
for(int i=0;i<10;i++)
stack.push(i);
for(int i=0;i<stack.getElement().length;i++)
System.out.println(stack.pop());
}
}
------解决方案--------------------
有两个错误
public StackOfInteger(int capacity)
{
element=new int[capacity];
// int[] element=new int[capacity]; //定义了局部变量,把字段隐藏了
}
public static void main(String[] args) {
StackOfInteger stack=new StackOfInteger();
for (int i=0; i<10; i++)
stack.push(i);//入栈10次
for (int i=0; i<stack.getElement().length; i++)//stack.getElement().length=16
System.out.println(stack.pop());//出栈16次,会有ArrayIndexOutOfBoundsException
}