-2

我写了一个做不同事情的类。我正在尝试使用循环来计算数组列表中的用户数。基本上,班级正在获取信息并添加有关学生的信息。输入的内容之一是学生所学的学分。假设我在我的数组列表中输入了 5 个学生。两个学生修了 5 个学分 2 个学生修了 6 个学分,最后一个学生修了 9 个学分。我在课堂上创建了一些代码,假设用户想知道数组中有多少学生正在学习 6 个学分。所以我创建了一个段,让用户输入该数字,班级将在数组中查找并返回有多少学生正在使用该数字,但它不起作用。我不知道这是否有意义

System.out.print("Please enter a number of credits:\n");
inputInfo = stdin.readLine().trim();
int credits = Integer.parseInt(inputInfo);

int count = 0;


for (int i = 0; i < studentList.size(); ++i)
{
  count++;
}   


System.out.println("The number of students who are taking " + credits
                               + " credits is: " + count);

break; 
4

4 回答 4

1

对于每个学生,您必须检查他是否拥有与您正在寻找的相同数量的学分。

for循环替换为:

/* If your list contains an array of Student objects */
for(Student student : studentList) {
   if (student.getCredits() == credits) {
       count++;
   }
}

/* If you don't use objects */
for(int i = 0; i < studentList.size(); i++) {
   if(studentList[i].credits == credits) {
       count++;
   }
}
于 2013-09-18T22:39:21.027 回答
1

您永远不会真正检查他们是否获得了正确数量的学分。把它放在你的循环中:

if(studentList[i].credits == credits) {
    count++;
}
于 2013-09-18T22:40:01.080 回答
0

您需要检查学生的学分是否符合要求的值。像这样的东西:

for (int i = 0; i < studentList.size(); ++i)
{
  if(studentList[i].credits == credits)
    count++;
}   
于 2013-09-18T22:42:13.713 回答
0

您需要检查某个索引的学生是否具有您正在寻找的学分数量。如果它刚刚增加了计数器,否则继续循环遍历列表直到列表末尾。

System.out.print("Please enter a number of credits:\n");
inputInfo = stdin.readLine().trim();
int ncredits = Integer.parseInt(inputInfo);
int count = 0;

for (int i = 0; i < studentList.size(); i++){
    // if the student at this index has ncredits
    // then

    count++;
}   


System.out.println("The number of students who are taking " + credits
                           + " credits is: " + count);
于 2013-09-18T22:42:49.467 回答