![](/img/trans.png)
[英]What should I put in the if statement to get the subclass object element?
[英]Calculate the number of students who passed - what should I put in the if statement?
這個想法是將學生添加到數組列表中,計算出通過的學生人數,然后返回該人數。 我認為隨着代碼的工作,我快到了,但是它總是為數組列表中的數量返回相同的值-顯然,這是不正確的。 我已經這樣做了幾個小時,我看不到if語句中缺少的語句可以完成它! 我對此表示感謝!
import java.util.ArrayList;
class Course
{
private ArrayList<Student> people = new ArrayList<Student>();
//Add a students mark
public void add( Student s )
{
people.add(s);
}
//Return the number of students who passed (mark>= 40)
public int pass()
{
int size = people.size();
int i = 0;
int result = 0;
for (i = 0; i < size; i++)
{
Student s = people.get(i);
if(s.getMark() >= 40);
{
// what's here?
}
return result;
}
}
}
在pass方法中刪除此語句
ArrayList people = new ArrayList();
由於該語句,在調用pass方法時,您的局部變量隱藏了實例變量。
您在pass()
方法中聲明了一個重復的空people
列表。 去掉它。
您創建一個不包含任何元素的ArrayList
,然后從中創建Object[]
類型的result
,該結果的長度為0。
ArrayList people = new ArrayList();
Object result[] = people.toArray();
因此,您的for循環將根本不會執行。
您可能想訪問實例變量people
,可以通過
ArrayList people = new ArrayList();
從方法 this
: Object result[] = this.people.toArray();
首先,您兩次指定ArrayList people
,一次在pass方法之外,第二次在pass方法內部。 pass方法默認使用其中的一個,它為空。
標記始終為0
。 因此,這不起作用:
if ( mark >= 40)
在完成for循環之后,您應該返回結果,並且應該增加result
而不是i
:
public int pass()
{
int size = people.size();
int result = 0;
for (int i = 0; i < size; i++)
{
Student s = people.get(i);
if(s.getMark() >= 40);
result++;
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.