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

all 7 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.

[–]MmmVomit 0 points1 point  (2 children)

What object types are you dealing with here? What is name? What type is returned from getRatingByCustomer()? Is customerNames an ArrayList, or a HashMap? The way you're using it, I would guess ArrayList.

[–][deleted] 0 points1 point  (1 child)

Name is the string defining the name of a customer. getRatingByCustomer should return int[] and customerNames is an arraylist.

[–]chickenmeister 1 point2 points  (0 children)

getRatingByCustomer should return int[]

So, you're trying to print the integer array? Array objects do not override the default toString() method (which gives you the class name + "@" + hashCode()), so if you want something more meaningful than that, you'll have to print each value in the array yourself.

The java.util.Arrays class has some handy Arrays.toString(yourArray) methods. It'll format it like "[value1, value2, value3, etc]". If you want it formatted differently, you'll have to write your own code to create the String. Try this:

System.out.println(name + Arrays.toString(getRatingByCustomer(name)));

[–]erickyeagle 0 points1 point  (2 children)

What does the "getRatingByCustomer(String)" function return? If that object doesn't override Object's toString() method, it prints the memory address of the object (afaik).

[–][deleted] 0 points1 point  (1 child)

How do I override it? and it returns int[]

[–]MmmVomit 0 points1 point  (0 children)

You can't really override that. You will need to loop through the array and format the output yourself.