Home > Software engineering >  Average numbers in Java without scanner
Average numbers in Java without scanner

Time:04-02

i am trying to get the numbers from me and made an average but without the scanner utility.

Actually Bluej allows me to put the number to rate but if i am trying to put again it replaces the previous one, i want to be stored and after that an average to be shown.

I can't figure out how to do it

I am using BlueJ.

This is the part of code:

    public int getRate() // here i put an int number
{
    return this.rate;
}

public void setRate(int rate) // here i change it but i think i don't need it
{
    this.rate = rate;
}

I can't use strange or complex commands because i am allowed to only use this type of commands like get/set and arraylists.

It is a school assignment.

Thanks

CodePudding user response:

An easy way to keep an average of inputs is to keep track of:

  1. The sum of all inputs received so far.
  2. The number of inputs you have received.

Every time you call setRate to update the rate, you add to the sum and increment the count. You also need a special case for when no rates have been added yet, to avoid division by zero:

private int ratesSum = 0;
private int rateCount = 0;

public int getRate()
{
    return this.rate;
}

public void setRate(int rate)
{
    this.rate = rate;
    this.ratesSum  = rate;
    this.rateCount  ;
}

// Gets the average of all rates so far, or returns zero if no rates
// have been set yet.
public float getAverageRate()
{
    // Do not divide by zero
    if (rateCount == 0) return 0;

    return ((float)ratesSum) / ((float)rateCount);
}
  • Related