public class Stack {
Student Sarray[] = new Student[1000];
int nrElem=0;
public Student[] getAll(){
return this.Sarray;
}
public void push(Student x){
this.nrElem++;
this.Sarray[this.nrElem]=x;
}
}
我尝试手动实现一个堆栈,我有一个小问题。我插入的第一个元素存储并替换,当我插入另一个。我做错了什么?堆栈模拟不存储元素
public class Ctrl {
Stack x = new Stack();
public void addC(Student s){
if(findById(s.getId()) != null) {
System.out.println("Err!Duplicate id!/n");
} else {
if(s.getGrade()>10)
System.out.println("Err!Grade bigger than 10!/n");
else{
x.push(s);
}
}
}
public Student findById(int id){
Stack y=new Stack();
y=x;
Student z= new Student() ;
for(int i=1;i<=y.getNrElem();i++){
z=y.pop();
if (z.getId()==id)
return z;
}
return null;
}
2个不同的Stack和Ctrl模块。现在
Stack y=new Stack(); // creates new reference to new Stack ...
y=x; // reference is redirected to point to the class's Stack instance
Ÿ指向类成员X,你在弹出for循环follwing空:
也许你是错误地停止一个新的Stack对象? –
你的代码存在问题,在push方法中,nrElem的增量必须是在赋值后,或者thisSarray [this.nrElem ++] = x',但是我们需要查看所有其他方法来查看错误在哪里,你没有显示findById – RamonBoza
@RamonBoza更新了'findById()' – Matt