copernicon1543
copernicon1543

Reputation: 45

Passing and updating an array of scores by increasing with given percentage

public class ScoreCard {

private double[] scores;
/**
 * 
 * @param val
 * @param low
 * @param high
 * @return low if val < low, 
 * high if val > high, 
 * val if val is between low and high
 */
private double constrain(double val, int low, int high) {
    if (val < low)
        return low;
    if (val > high)
        return high;
    return val;
    }

.
.
.
.

/**
 * update each score so it increases by given percentage. For example,
 * if score = {60.0, 90.0} before the method is called, it should
 * become {72.0, 100.0} after the method is called with parameter 20.
 * Note: 90.0 increased by 20% is 108, but scores should be constrained between
 * 0 and 100. So, 100.
 * @param percentage
 */

public void scale(double percentage) {
    for (int i = 0; i < scores.length; i++) {
        percentage = scores[i] / 100.0 * percentage;
        scores[i] += constrain(percentage, 0, 100);
        }
    }

I've been stuck again on a little piece of code for a project. I am failing the JUnit tests when I try and pass this function. It seems to be correctly updating array with given percentage (10%) but instead of each item updating by the given percent, it seems to divide the percentage between the items inside the array, giving me ugly numbers.

Any assistance would be greatly appreicated!

Upvotes: 0

Views: 570

Answers (2)

user813512
user813512

Reputation:

public void scale(double percentage) {
    for (int i = 0; i < scores.length; i++) {
        percentage = scores[i] / 100.0 * percentage;

        scores[i] =(scores[i]+percentage)>=100?100:(scores[i]+percentage);
        }

    }

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 9650

Why are you changing the value of percentage in the loop? I would do something like so:

for (int i = 0; i < scores.length; i++) {
    scores[i] = constrain(scores[i]*(1+percentage/100), 0, 100);
}

Upvotes: 1

Related Questions