Java - 如何在另一个类中调用add()方法

时间:2016-02-05 21:02:24

标签: java class object add indexoutofboundsexception

这是为了做作业,我对如何弄清楚如此简单的事情感到有点沮丧。

为了简化我的代码,我现在有3个文件:一个带有我创建的add()方法的类,一个测试它的文件(由prof创建),以及一个创建对象的文件(我不会发布,b / c其工作)。这是add()函数。

编辑2:我要添加打印数组的方法,也许这就是问题?

    public class Population {
      private Person[] pop = new Person[15];
      private int numPop = 0;    

      public void add(Person c){ // this object is created in another class, it works fine
        for(int i = 0; i < pop.length; i++){
          if(pop[i] == null) {
            pop[i] = c;
            numPop++;
          } else {}
        }

 public String listPeople(){
      System.out.println("Population with "+numPeople+" people as follows:");
      int i = 0;
      while (i<numPeople){
       System.out.println("A "+pop[i].getAge()+"year old person named "+pop[i].getName());
        i++;
//FYI the get methods are working fine and are in another file.
 } 
      return("");
      }

然后,我在测试文件中运行该程序以确保它可以正常工作,这是提供给我们的。这是不起作用的部分

public class PopTestProgram{ // FYI the prof created this, I can't change this
  public static void main(String[] args){

    Population pop = new Population(15);

    pop.add(new Person(4, "Bob"));
    pop.add(new Person(25, "Kim"));
    // then adds 8 more people with different ages and names
    // then prints the people

它编译,但是当我运行它时,它只是将最后一个人中的10个放入数组中,然后崩溃说"pop[i] = c;"行存在问题。我根本无法弄清楚我需要在这里改变什么。

我没有直接收到教授的电子邮件,所以我想我会在这里问。

编辑:这是在将最后一个人打印10次后显示的内容。它显示了我还没有完成的其他方法的问题......

java.lang.ArrayIndexOutOfBoundsException: -1
    at Population.removePerson(Population.java:49)
    at PopTestProgram.main(PopTestProgram.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

2 个答案:

答案 0 :(得分:1)

在添加(Person)中,当你添加一个项目时你没有停止,所以你添加的第一个项目放在数组中的所有单元格中,然后其余部分根本不会进入,因为没有更多数组中的null单元格。找到空位置时打破循环。

public void add(Person c) {
    for(int i = 0; i < pop.length; i++){
      if(pop[i] == null) {
        pop[i] = c;
        numPop++;
        break;
      }
      else {
        //.....
      }
   }
}

也可以使用numPop作为列表中的下一个位置,例如:

public void add(Person c) {
    if (numPop < pop.length) {
       pop[numPop++] = c;
    }
}

答案 1 :(得分:0)

异常发生在Population.removePerson(Population.java:49),与add方法无关。所以我假设removePerson是打印此人的方法。 在移除你正在调用一个额外的For循环时,请确保您的迭代仅 10 次。

java.lang.ArrayIndexOutOfBoundsException: -1清楚地告诉 removePerson 方法也调用索引-1 (它不存在导致ArrayIndexOufofBoundsException)。 removePerson方法应该从索引9开始到索引0(或反之)[总共10次迭代],然后停止。

希望这有帮助