title: Java] How to calculate average score by subjects (using ArrayList)
body: <p>I'm trying to figure out if there's a way to calculate total and average scores by subjects (not by students!). FYI, I wrote this code while I was studying <code>ArrayList</code>.</p>
  <p>Here's the codes I'm working on. The result I wanna get is <code>mathTotal: 180, korTotal: 150, engTotal: 90</code> &amp; <code>mathAvg: 90, korAvg: 75, engAvg: 90</code>.</p>
  <pre class="lang-java prettyprint-override"><code>public class Subject {
  
      private String subjectName;
      private int score;
      
      public Subject(String subjectName, int score) {
          this.subjectName = subjectName;
          this.score = score;
      }
      
      public String getSubName() {
          return subjectName;
      }
      
      public int getScore() {
          return score;
      }   
  }
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>import java.util.ArrayList;
  
  public class Student {
      private int studentID;
      private String studentName;
      ArrayList&lt;Subject&gt; subjectList;
      
      public Student(int studentID, String studentName) {
          this.studentID = studentID;
          this.studentName = studentName;
          subjectList = new ArrayList&lt;Subject&gt;();
      }
      
      public void addSubject(String subjectName, int score) {
          Subject subject = new Subject(subjectName, score);
          
          subjectList.add(subject);
      }
      
      public void calcScore() {
          int total = 0;
          double subCnt = 0;
          
          System.out.println(&quot;&lt; &quot;+studentName+&quot;'s score &gt;&quot;);
          for (Subject subject: subjectList) {
              total += subject.getScore();
              System.out.println(subject.getSubName()+&quot;: &quot;+subject.getScore());
              subCnt++;
          }
          double average = total/subCnt;
          String averageCut = String.format(&quot;%.2f&quot;, average);
          System.out.println(&quot;total: &quot;+total);
          System.out.println(&quot;average: &quot;+averageCut);
      }
  }
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>public class StudentTest {
      public static void main(String[] args) {
          
          Student student1 = new Student(1001, &quot;Amy Park&quot;);
          Student student2 = new Student(1005, &quot;Steven Yeun&quot;);
          
          student1.addSubject(&quot;Math&quot;, 80);
          student1.addSubject(&quot;Korean&quot;, 90);
          
          student2.addSubject(&quot;Math&quot;, 100);
          student2.addSubject(&quot;Korean&quot;, 60);
          student2.addSubject(&quot;English&quot;, 90);
          
          student1.calcScore();
          student2.calcScore();
      }
  }
  
  </code></pre>