2013-10-24 59 views
0
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空:

+0

也许你是错误地停止一个新的Stack对象? –

+6

你的代码存在问题,在push方法中,nrElem的增量必须是在赋值后,或者thisSarray [this.nrElem ++] = x',但是我们需要查看所有其他方法来查看错误在哪里,你没有显示findById – RamonBoza

+0

@RamonBoza更新了'findById()' – Matt

回答

1

public Student findById(int id)你做到这一点。 这意味着如果您使用参考号y对数据结构进行了更改,则将使用参考号x来查看这些更改,因为您正在对同一个实例进行更改。

您可以在堆栈类中执行不会更改堆栈内容的搜索,也可以在您的堆栈的副本上执行此操作。大多数情况下,这是通过在DataStructure的类中提供“Copy”构造函数或“clone()”方法来实现的。

例如改变上述行

Stack y = new Stack(x); 
// y=x We do not need this any more. 

而在栈类中添加:

public Stack(Stack aStack) { 
    System.arraycopy(aStack.Sarray,0,this.Sarray,0,aStack.Sarray.length); 
    // By the way: please start members with a small letter! 

    this.nrElem = aStack.nrElem; 
} 

P.S:并注意RamonBoza的评论,+1他。

1

您正在使用addC插入学生的方法。 它依次调用findById,其中包含以下行:

z=y.pop() 

对于简单的情况下,有一个在你的流行出栈一个元素,但从来没有将其推回。 所以要修复它,您需要在弹出它们之后将元素返回到堆栈,或者在类Stack中找到一个方法,该方法可以在不弹出元素的情况下找到元素。

顺便说一句,你还没有提供代码getNrElem()方法。