0

I am faced with probably a very simple dilemma. I am trying to create a program that computes the averages, sums, and count of all numbers inputed to the calculator. The problem with this is that I can only accept one input or three (dependent on number of variables listed in my method parameters). How do I make my add() method actually accept n number of inputs as opposed to a predefined set?

Main Class

public class Calculator 
{
    public static void main (String [] args)
    {
        AverageCalculator calculation1 = new AverageCalculator();
        AverageCalculator calculation2 = new AverageCalculator();

        calculation1.add(13);
        System.out.println("Sum: " + calculation1.getSum());
        System.out.println("Count: " + calculation1.getCount());
        System.out.println("Average: " + calculation1.getAverage());

        System.out.println();

        calculation2.add(3, 7, 12); // Error due to method parameters
        System.out.println("Sum: " + calculation2.getSum());
        System.out.println("Count: " + calculation2.getCount());
        System.out.println("Average: " + calculation2.getAverage());
    }
}

I get an error when compiling this:

Calculator.java:28: error: method add in class AverageCalculator cannot be applied to given types;
        calc2.add(3, 7, 12);

I am then running into how am I going to deal with my add() method's functionality. I know what it must do, I am sure I must add a for Loop. However, there is no given length for it to parse. Do I have my i = 0; i < calculation 2; i++? See comments in this portion

Secondary Class

public class AverageCalculator 
{
    private int sum;
    private int count;

    public AverageCalculator () {}

    public void add (int newNum) // One input due to single parameter
    {
        // How to accept the multiple input from main class with this mutator
        // and successfully manipulate data in this method
        sum += newNum;
        count++;
    }
    public int getSum()
    { return sum; }

    public int getCount()
    { return count; }

    public double getAverage()
    { return (double) sum / count; }
}
Computer
  • 132
  • 11
  • 1
    This is called _varargs_.Please have a look at ["When do you use varargs in Java?"](http://stackoverflow.com/questions/766559/when-do-you-use-varargs-in-java) – Seelenvirtuose Jun 12 '16 at 06:50
  • There is similar question. Refer to under link. http://stackoverflow.com/questions/17837117/java-sending-multiple-parameters-to-method – Junho Cha Jun 12 '16 at 07:28

1 Answers1

1

Java supports this. Is is called "varargs". If you add "..." to your type, you can repeat it as many times as you want (including 0 times) and then, in your function, process it as an array. This could like this (this code is completely untested):

public void add(int... newNums) {
    for (int num : newNums) {
        sum += num;
        count++;
    }
}

A you can read a bit more here.

Leon
  • 2,926
  • 1
  • 25
  • 34