본문 바로가기
공부/Object-Oriented Design Pattern

For this problem you must define a simple interface NumTrackerInterface and two implementations of the interface,

by 혼밥맨 2022. 3. 12.
반응형

For this problem you must define a simple interface NumTrackerInterface and two implementations of the interface, Tracker1 and Tracker2.

 

a. Define a Java interface named NumTrackerInterface. A class that implements this interface must keep track of both the sum and the count of numbers that are submitted to it through its add method, and provide getters for the sum, the count, and the average of those numbers. The add method should accept an argument of type int, the getSum and getCount methods should both return values of type int, and the getAverage method should return a value of type double. Suppose a class named Tracker1 implements the NumTrackerInterface. A simple application that uses Tracker1 is shown here. Its output would be "3 29 9.67"

 

 

A) package List;

interface NumTrackerInterface {

    void add(int n);

    int getCount();

    int getSum();

    double getAverage();

}

 

class Tracker1 implements NumTrackerInterface {

    int count, sum;

 

    double avg;

 

    @Override

    public void add(int n) {

        count = count + 1;

        sum = sum + n;

        avg = sum * 1.0/count;

    }

 

    @Override

    public int getCount() {

        return count;

    }

 

    @Override

    public int getSum() {

        return sum;
    }

 

    @Override

    public double getAverage() {

        return Math.round(avg * 100.0) / 100.0;

    }

 

    public class Sample {

        public static void main (String[] args) {

        NumTrackerInterface nt = new Tracker1();

        nt.add(5);

        nt.add(15);

        nt.add(9);

        System.out.println(nt.getCount() + " ");

        System.out.println(nt.getSum() + " ");

        System.out.println(nt.getAverage());

    }

}

 

 

반응형

댓글