简体   繁体   English

数组列表-级别的大小?

[英]Array list - size of level?

As part of my homework I have the following code: 作为作业的一部分,我有以下代码:

  ArrayList <Integer> marks = new ArrayList();

  Collections.addAll(marks, (Integer.parseInt(markInput.getText())));

  private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) 
  {
      analyzeTextArea.setText("Number at level R:" + calculateLevelR());
  }

  private int calculateLevelR() {
      int sum = 0;
      for (Integer mark: marks) {
          if(mark < 50)
              sum += mark;
          sum = marks.size();
      }
      return sum;
  }

When a user enters a set of grades, I'm trying to calculate and display the amount of grades that are "level R" (under 50) but the above code does not work properly, instead it calculates the size of the whole array. 当用户输入一组等级时,我试图计算并显示“ R级”(低于50)的等级数量,但是以上代码无法正常工作,而是计算整个数组的大小。

How can I get it to calculate just the amount of grades at "level R"? 我怎样才能只计算“ R级”的成绩?

Other answers have already pointed out the exact problem, looking at your comments may be a code snippet can explain better. 其他答案已经指出了确切的问题,查看您的注释可能是代码片段可以更好地说明。 See below 见下文

  private int calculateLevelR() {
      int sum = 0;
      for (Integer mark: marks) {
          if(mark < 50)
              sum += mark;
          sum = marks.size(); // If mark is less than 50 add mark to sum else sum = size of arrayList
      }
      return sum;
  }

What you need is : 您需要的是:

  private int calculateLevelR() {
      int sum = 0;
      for (Integer mark: marks) {
          if(mark < 50)
              sum++; // If mark is less than 50 increment sum
      }
      return sum; // finally when check all marks return sum, this sum will represent total number of marks less than 50.
  }

Maybe because you have this sum = marks.size(); 可能是因为您有这个sum = marks.size(); right after this sum += mark; 就在这个sum += mark; in your loop. 在你的循环中。

In addition you should sum grades amount, not value, so you should add just 1 if a mark is under 50 (eg. ++sum ), not the actual mark. 另外,您应该对成绩的数量求和,而不是对值求和,因此,如果分数低于50(例如++sum ),则应该仅加1,而不是实际分数。

Thats because you are setting sum to marks.size() after the call to sum += mark; 那是因为您在调用sum + = mark之后将sum设置为marks.size(); Just remove the som= marks.size() line. 只需删除som = marks.size()行即可。

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

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