0

I have a method that looks like

public double calculator(Iterable<Integer> userRating)

I'm trying to implement logic that removes the highest and lowest values and calculate the average. The end result should look like (removing the mins -2, and maxs 15)

public void ProperlyCalculates() {
        List<Integer> ratings = new ArrayList<Integer>();
        ratings.add(-2);
        ratings.add(-2);
        ratings.add( 3);
        ratings.add( 7);
        ratings.add( 8);
        ratings.add( 9);
        ratings.add(15);
        ratings.add(15);
        ratings.add(15);
        double rating = rater.getMovieRating(ratings);
        assertEquals(6.75D, rating, 0.0000001D);

I'm confusing myself trying to create an iterator that I can loop through and add in my logic. So far I have tried.

public double getMovieRating(Iterable<Integer> userRating) {


        Iterator ratings = userRating.iterator();
        int min = Integer.MIN_VALUE;
        int max = Integer.MAX_VALUE;

        while (ratings.hasNext()) {
            Integer val = ratings.next();
            if (val > max){ max = val;}
            if (val < min) {min = val;}  

        }

    }

But Integer val = ratings.next() throws an incompatible type error. How can I can loop through all of the values in the iterator? Is this a case where I would need a private inner class?

idclark
  • 948
  • 1
  • 8
  • 27
  • possible duplicate of [Calling remove in foreach loop in Java](http://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java) – idclark Jun 14 '14 at 00:02

2 Answers2

2

There are 2 ways you can fix this problem. Either provide a type for the Iterator, like this

Iterator<Integer> ratings = userRating.iterator(); // An iterator of type Integer

or cast the value returned from the iterator.next() to an Integer, like this

Integer val = (Integer) ratings.next();

In the first case, you ensure that every element returned by the Iterator will be of the type Integer only. And in the second case, you cast the value to an Integer because an Iterator without a type would return an Object by default.

Rahul
  • 44,383
  • 11
  • 84
  • 103
1

In addition to what @R.J said, you should also consider using for:next syntax, as it makes this much simpler:

public double getMovieRating(Iterable<Integer> userRating) {

    int min = Integer.MIN_VALUE;
    int max = Integer.MAX_VALUE;

    for(Integer rating : userRating) {
        final int val = rating.intValue();
        if (val > max){ max = val;}
        if (val < min) {min = val;}  
    }
}
Brett Okken
  • 6,210
  • 1
  • 19
  • 25