这个想法是将学生添加到一个arraylist,计算已经通过的学生人数,并返回该数字。 我认为我几乎就在那里,因为代码有效,但它总是返回数组列表中数量的相同值 - 显然,这是不正确的。 我已经这样做了好几个小时了,我无法看到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;
}
}
}
答案 0 :(得分:1)
在pass方法
中删除此语句ArrayList people = new ArrayList();
由于这个语句,当调用pass方法时,你的局部变量会隐藏实例变量。
答案 1 :(得分:1)
您在people
方法中声明了一个重复的空pass()
列表。删除它。
答案 2 :(得分:1)
您创建一个没有元素的ArrayList
,然后从中创建result
类型Object[]
,其长度为0.
ArrayList people = new ArrayList();
Object result[] = people.toArray();
因此,你的for循环根本不会被执行。
您可能想要访问实例变量people
,您可以通过
ArrayList people = new ArrayList();
this
:Object result[] =
this.people.toArray();
答案 3 :(得分:1)
首先,指定ArrayList people
两次,一次,在pass方法之外,第二次在pass方法内。 pass方法默认使用其中的一个,它是空的。
答案 4 :(得分:0)
标记始终为0
。所以这不起作用:
if ( mark >= 40)
答案 5 :(得分:0)
您应该在完成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;
}