Home > Net >  How do I find the maximum and the average for 3 weights (pounds,ounces) I have a program that compar
How do I find the maximum and the average for 3 weights (pounds,ounces) I have a program that compar

Time:04-03

I need help figuring out how to find the average and the maximum weight. Down below you will see the methods templates I have created; However, I can't figure out how to find the max and average weight.

public static void main(String[] args) {
    Weight weight1 = new Weight(4, 13);
    Weight weight2 = new Weight(4, 1);
    Weight weight3 = new Weight(14, 10); // 14 lbs 10 ounces

    System.out.println(weight1   ", "   weight2   ", "   weight3);
    System.out.println("Minimum: "   findMinimum(weight1, weight2, weight3));
    System.out.println("Average: "   findAverage(weight1, weight2, weight3));    
}

private static Weight findMinimum(Weight weight1, Weight weight2, Weight weight3) {
    if(weight1.lessThan(weight2)) {
        if (weight1.lessThan(weight3)) {
            return weight1;
        }
        else {
            return weight3;
        }
    }
    else {
        if(weight2.lessThan(weight3)) {
            return weight2;
        }
        else {
            return weight3;
        }
    }
}

private static Weight findMaximum(Weight weight1, Weight weight2, Weight weight3) {
    
}
    
private static Weight findAverage(Weight weight1, Weight weight2, Weight weight3){
    Weight results=new Weight(0,0);
    results=  weight1;
}

CodePudding user response:

For min and max, first create a function that compares Weight:

public class WeightComparator implements Comparator<Weight> {
    int compare(Weight w1, Weight w2) {
        // return -1 if w1 is higher
        // return 0 if they are equal
        // return 1 if w2 is higher
    }
}

With that you can start sorting your weights. For example, put them in a collection and use sort:

ArrayList<Weight> list = new ArrayList<>();
list.add(new Weight(...));
list.add(new Weight(...));
list.add(new Weight(...));
Collections.sort(list, new WeightComparator());

Once done, the min is the first element, the max the last element of your list.

For the average, just sum up all the elements, then divide by their count.

public Weight getAverage(List<Weight> list) {
    int pounds = 0;
    int ounces = 0;

    for (Weight w: list) {
        pounds  = w.getPounds();
        ounces  = w.getOunces();
    }

    return new Weight(pounds / list.size(), ounces / list.size);
}

CodePudding user response:

Your logic should simply be:

findMaximum(w1, w2, w3) {
    if (w1 > w2 and w1 > w3) {
        return w1
    }
    if (w2 > w1 and w2 > w3) {
        return w2
    }
    if (w3 > w1 and w3 > w2) {
        return w3
    }
}


findAverage(w1, w2, w3) {
    return (w1 w2 w3) / 3
}
  • Related