【发布时间】:2016-02-05 21:02:24
【问题描述】:
这是做作业的,我对自己无法弄清楚这么简单的事情感到有点沮丧。
为了简化我的代码,我现在有 3 个文件:一个具有我创建的 add() 方法的类,一个测试它的文件(由教授创建),以及一个创建对象的文件(我不会发布,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)
【问题讨论】:
-
你得到的确切异常是什么?
-
是的,展示整个该死的东西!
-
从 'new Person(4, "Bob"));' 传递的内容看起来像一个错误线。你能展示一下方法吗,或者至少展示一下错误发生时'c'的值是什么?
-
如果你真的想要它,我会发布异常,但我玩弄了我的代码,现在它没有显示我想看到的异常......它显示了不同的异常我还没有完全完成的方法。
-
这不是答案,而是
for循环,您应该使用while循环在pop中查找null值的索引并使用该值在该循环之外。这样,一旦找到该索引,就不必遍历数组的其余部分。
标签: java class object add indexoutofboundsexception