简体   繁体   English

如何找到数组列表中属于某个范围的元素数?

[英]How to find the number of elements in an arraylist that falls into a certain range?

I'm making a program which allows the user to enter in mark values, and it outputs the number of students in a certain mark range. 我正在制作一个程序,允许用户输入分数值,并输出一定分数范围内的学生人数。

Ex. 例如 Level 2 ( (mark >= 60) && (mark < 70) ) 级别2((mark> = 60)&&(mark <70))

Level 3 ( (mark >= 70) && (mark < 80) ) 3级((标记> = 70)&&(标记<80))

Level 4 (mark >= 80). 级别4(标记> = 80)。

I thought of using a for loop and if statements to see which range each mark falls into, but I can't figure out how to count how many of them fall into which category. 我想到了使用for循环和if语句查看每个标记属于哪个范围,但是我不知道如何计算其中有多少属于哪个类别。

ArrayList<Integer> marks = new ArrayList<>();

 private void btnSortActionPerformed(java.awt.event.ActionEvent evt) {                                        

    Collections.sort(marks);
    String output = "";
    for (int i=0; i<marks.size(); i++) {
        output += marks.get(i) + "\n";
    }
    txtOutputSort.setText(output);
}       

You can use an array of ints for each count. 您可以为每个计数使用一个整数数组。 For example (if you have 2 levels): 例如(如果您有两个级别):

ArrayList<Integer> marks = new ArrayList<>();
int[] marksCount = new int[2];
//initialize each int in marksCount
for (int i=0; i<marksCount.length; i++) {
marksCount[i] = 0;
}
...
for (int i=0; i<marks.size(); i++) {
if(marks.get(i)<60)
marksCount[0]++;
else if(marks.get(i)>=60 && marks.get(i)<70)
marksCount[1]++;

Now, you have the marks of each level counted and stored within the marksCount array. 现在,您已经计算了每个级别的标记并将其存储在marksCount数组中。

The idea of using a for loop with if-else cases is a viable option. if-else情况下使用for loop的想法是一个可行的选择。 For the ranges that you have provided, the following code should work. 对于您提供的范围,以下代码应该起作用。

int marks_60_70 = 0;
int marks_70_80 = 0;
int marks_80 = 0;  

for(int mark: marks) {
    if((mark >= 60) && (mark < 70)) {
        marks_60_70++;
    } else if ((mark >= 70) && (mark < 80)) {
        marks_70_80++;
    } else if(mark >= 80) {
        marks_80++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM