![](/img/trans.png)
[英]How to call another method from a different class in the same java project
[英]Java - how to call an add() method in a different class
這是為了做作業,我對如何弄清這么簡單的東西感到沮喪。
為了簡化我的代碼,我現在有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;"
有問題"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)
在add(Person)中,添加項時不會停止,因此添加的第一個項將放入數組的所有單元格中,因此其余項將根本不會進入,因為在其中不再有空單元格數組。 找到空位置時,請中斷循環。
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;
}
}
例外情況出現在Population.removePerson(Population.java:49)
,它與add方法無關。 因此,我假設removePerson是打印人的方法。 刪除時,您要調用一個額外的For循環 ,請確保您的迭代僅10次。
java.lang.ArrayIndexOutOfBoundsException: -1
清楚地告訴removePerson方法也正在調用索引-1 (不存在導致ArrayIndexOufofBoundsException)。 removePerson方法應從索引9開始到索引0(反之亦然)[總共進行10次迭代],然后停止。
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.