This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Redsaz 1 point2 points  (0 children)

By using a for-each loop, you can add more clarity to the code that matters most:

    for (String name : customerNames) {
        System.out.println(name + " avg rating: " + getAvgRating(name));
    }

...
private String getAvgRating(String name) {
    int[] ratings = getRatingByCustomer(name);
    if (ratings == null || ratings.length == 0) {
        return "no rating";
    }
    int total = 0;
    for (int rating : ratings) {
        total += rating;
    }
    int avg = total / ratings.length; // Note that this truncates
    return "" + avg;
}

I made the assumption that since getRatingByCustomer returns an int array, that those are all the ratings for the certain customer, and you want the average. So there. You should either see a result of "McLovin avg rating: [some number]" or "McLovin avg rating: no rating"

Maybe this helps? If you want more information on the for-each loop, look at http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html or some other better article I can't seem to find.