|
| 1 | +package com.codefortomorrow.advanced.chapter15.solutions; |
| 2 | +import java.util.Arrays; |
| 3 | +/* |
| 4 | +Create a Measurable interface |
| 5 | +that is used to “measure” anything. Add necessary methods. |
| 6 | +Required Methods: double average(Measurable[] items), |
| 7 | +largest(Measurable[] items) or smallest(Measurable[] items). |
| 8 | +Create a Student class that implements Measurable and |
| 9 | +it’s methods(you can compare whatever you measure, i.e. GPA). |
| 10 | +Note: for the largest/smallest methods don’t worry |
| 11 | +about the case if they are equal. |
| 12 | +
|
| 13 | +Problem adapted from Java SE 9 Textbook |
| 14 | +*/ |
| 15 | +public class MeasurableProblem{ |
| 16 | + public static void main(String[] args){ |
| 17 | + Object[] students = { |
| 18 | + new Student("John", 2.7), |
| 19 | + new Student("Josh", 1.2), |
| 20 | + new Student("Jacob", 3.4), |
| 21 | + new Student("Rebecca", 3.5), |
| 22 | + new Student("Arnav", 4.0) |
| 23 | + }; |
| 24 | + Student test = new Student(); |
| 25 | + System.out.println("Average: " + test.average(students)); |
| 26 | + System.out.println("Largest: " + test.largest(students)); |
| 27 | + System.out.println("Smallest: " + test.smallest(students)); |
| 28 | + } |
| 29 | +} |
| 30 | +interface Measurable{ |
| 31 | + abstract double average(Object[] students); |
| 32 | + abstract String largest(Object[] students); |
| 33 | + abstract String smallest(Object[] students); |
| 34 | +} |
| 35 | +class Student implements Measurable{ |
| 36 | + private double GPA; |
| 37 | + private String name; |
| 38 | + public Student(String name, double GPA){ |
| 39 | + this.name = name; |
| 40 | + this.GPA = GPA; |
| 41 | + } |
| 42 | + public Student(){ |
| 43 | + name = ""; |
| 44 | + GPA = 0.0; |
| 45 | + } |
| 46 | + public double average(Object[] orig){ |
| 47 | + Student[] students = Arrays.copyOf(orig, orig.length, Student[].class); //Casting |
| 48 | + double sum = 0; |
| 49 | + for(Student s: students) |
| 50 | + sum += s.getGPA(); |
| 51 | + return sum / students.length; |
| 52 | + } |
| 53 | + public String largest(Object[] orig){ |
| 54 | + Student[] students = Arrays.copyOf(orig, orig.length, Student[].class); //Casting |
| 55 | + Student curr = students[0]; |
| 56 | + for(Student s: students){ |
| 57 | + if(s.getGPA() > curr.getGPA()) |
| 58 | + curr = s; |
| 59 | + } |
| 60 | + return curr.getName(); |
| 61 | + } |
| 62 | + public String smallest(Object[] orig){ |
| 63 | + Student[] students = Arrays.copyOf(orig, orig.length, Student[].class); //Casting |
| 64 | + Student curr = students[0]; |
| 65 | + for(Student s: students){ |
| 66 | + if(s.getGPA() < curr.getGPA()) |
| 67 | + curr = s; |
| 68 | + } |
| 69 | + return curr.getName(); |
| 70 | + } |
| 71 | + public double getGPA(){ |
| 72 | + return GPA; |
| 73 | + } |
| 74 | + public String getName(){ |
| 75 | + return name; |
| 76 | + } |
| 77 | +} |
0 commit comments