Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class GradeAnalyzer {
- //Constructor with no parameters
- public GradeAnalyzer(){
- }
- //Method with an ArrayList as a parameter. Produces error message if there are no elements in the ArrayList.
- public int getAverage (ArrayList<Integer> grades){
- if(grades.size()<1){
- System.out.println("Your array is empty");
- return 0;
- }else {
- int sum = 0;
- //For Each loop. "For each grade in the grades ArrayList..."
- for (Integer grade:grades){
- sum = sum + grade;
- }
- int average = sum / grades.size();
- System.out.println("The average of all of the grades is: " + average);
- return average;
- }
- }
- public static void main(String[] args) {
- //Create a new ArrayList (same process as creating a new instantiated object from your class)
- ArrayList<Integer> myClassroom = new ArrayList<>();
- myClassroom.add(98);
- myClassroom.add(92);
- myClassroom.add(88);
- myClassroom.add(75);
- myClassroom.add(61);
- myClassroom.add(89);
- myClassroom.add(95);
- //Create a new GradeAnalyser object, and instantiate
- GradeAnalyzer myAnalyser = new GradeAnalyzer();
- //Call the getAverage method, with the ArrayList as the parameter
- myAnalyser.getAverage(myClassroom);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement