-2

I have 2 instance variables.

private int ratingsTotal;
private int ratingsCount;

I have two methods.

Here is one.

public void rateStation(int rating)
{
   // ADD the rating that is SET to the ratingsTotal VAR
   // ADD 1 to the ratingsCount
   **// this.ratingsCount++; ??????**
}   

I figure it would be something like this:

if (rating < 6 && rating > 0)
    {
       this.ratingsTotal = rating;
        this.ratingsCount++;
    } else if (rating > 6 && rating < 0)
    {

    }

BUT how do I add the rating score to the ratingTotal var??

Here is the second method - I believe I have this right.

public double calcAvgRating()
{
    // check to see if there have been ratings
    // if so, calculate the average and assign to ratingsAvg
    // if not, leave ratingsAvg at -1.0 

    if (ratingsCount > 0)
    {
        double myRating = this.ratingsTotal / this.ratingsCount;
        return myRating;
    }else{
        return -1.0;
    }  
}
newJavaCoder
  • 93
  • 1
  • 8
  • you want something like this.ratingsTotal = this.ratingsTotal + rating; ?? – daremachine Mar 03 '15 at 01:36
  • @daremachine - thanks. That seems to work. However, since the instance variables are INT, I am not getting a good rating (double). My code within calcAveRating did not work.... – newJavaCoder Mar 03 '15 at 01:58

1 Answers1

1

you can use

this.ratingsTotal = this.ratingsTotal + rating;

e.g. ratingTotal increase with rated rating and then you upvote +1 in your vote.

for calculation you can retype (cast type as another type) your int to double simply by (double) before value. Java is strong type language but this cast type work in PHP too.

double myRating = (double) this.ratingsTotal / (double) this.ratingsCount;

second answer I need to convert an int variable to double

you can not forget treat exception Zero-divided and next you can round your result

http://www.tutorialspoint.com/java/number_round.htm

Community
  • 1
  • 1
daremachine
  • 2,678
  • 2
  • 23
  • 34
  • 1
    Another easy reference explaining integer vs double division and why the calculation appeared inaccurate is http://mathbits.com/MathBits/Java/DataBasics/Mathoperators.htm (short, geared towards beginners, @newJavaCoder should take a moment to read, at least the section titled "Confusing Divisions"). – Jason C Mar 03 '15 at 03:05