Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Average numbers in Java without scanner

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading