How do I display the sum of all positive numbers in the collection and the sum of all negative numbers using iterators?

ryanbecker24
ryanbecker24 used Ask the Experts™
on
This is my code:

/**
 * Using class with iterators
 */
import java.util.ArrayList;
import java.util.Iterator;

public class Numbers {
    private ArrayList<Double> numbers;
   

    public Numbers() {
        numbers = new ArrayList<Double>();
       
    }

    /**
     *Add a number to the collection in a client specified position or at the
     * end of the collection
     */
    public void addNumber(double number) {
        numbers.add(number);
    }

    /**
     * Display all numbers in the collection
     */
    public void displayNumbers() {
        Iterator<Double> it = numbers.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
           
        }
    }

    /**
     * Display all numbers in the collection organized in 2 categories, first
     * the positive numbers, second the negative numbers
     */
    public void displayNumbersInCategories() {
        double number = 0;
        System.out.println("Positive Numbers");
       

        Iterator<Double> it = numbers.iterator();

        while (it.hasNext())
        {number = it.next();
            if (number >= 0.0)
            {
               
                System.out.println(number);
            }

           
        }

        System.out.println("Negative Numbers");
       
        it = numbers.iterator();
       

        while(it.hasNext()) {
            number = it.next();
            if (number < 0.0) {
                System.out.println(number);
            }
        }
    }

    /**
     * Display the sum of all numbers in the collection
     */
    public void displaySum() {
        double sum = 0.0;
        Iterator<Double> it = numbers.iterator();

        while (it.hasNext()) {
           sum = sum + it.next();
       
        }

        System.out.println(sum);
    }

    /**
     * Display 2 sums: the sum of all positive numbers in the collection and the
     * sum of all negative numbers in the collection
     */
    public void displaySumsInCategories() {
        double number = 0;
        double sum = 0.0;
        Iterator<Double> it = numbers.iterator();
       
        System.out.println("Positive Numbers");

        while (it.hasNext()) {
            number = it.next();
            sum = sum + it.next();
           
        }

        System.out.println(sum);
        // }
        System.out.println("Negative Numbers");

        while(it.hasNext()) {
            number = it.next();
            sum = sum + it.next();
            {
                System.out.println(sum);
            }
        }
    }
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Expert of the Quarter 2010
Expert of the Year 2010

Commented:
You could use Math.max and min to "mask" the positive/negative numbers.

    /**
     * Display 2 sums: the sum of all positive numbers in the collection and the
     * sum of all negative numbers in the collection
     */
    public void displaySumsInCategories() {
        double number = 0;
        double sum = 0.0;
        Iterator<Double> it = numbers.iterator();
       
        System.out.println("Positive Numbers");

        while (it.hasNext()) {
            number = it.next();
            sum = sum + Math.max(it.next(),0);
           
        }

        System.out.println(sum);
        // }
        System.out.println("Negative Numbers");

        while(it.hasNext()) {
            number = it.next();
            sum = sum + Math.min(it.next(),0);
            {
                System.out.println(sum);
            }
        }

Open in new window

Expert of the Quarter 2010
Expert of the Year 2010
Commented:
Please ignore the previous post.
It had some syntax errors and is not efficient if you need both +ve and -ve in the same function.
It was also using it.next() twice each time, so you lose half the numbers.

The below collects both in one pass.
    /**
     * Display 2 sums: the sum of all positive numbers in the collection and the
     * sum of all negative numbers in the collection
     */
    public void displaySumsInCategories() {
        double number;
        double sumP = 0.0;
        double sumN = 0.0;
        Iterator<Double> it = numbers.iterator();

        while (it.hasNext()) {
            number = it.next();
            if(number>0) {
                sumP = sumP + number;
            } else {
                sumN = sumN + number;
            }
        }

        System.out.println("Sum of positive numbers: " + sumP);
        System.out.println("Sum of negative numbers: " + sumN);
    }

Open in new window

Mick BarryJava Developer
Top Expert 2010

Commented:
I posted how in your earlier question (where you accepted a comment that was incorrect)


public void displaySumsInCategories()  
{
   double sum1 = 0;
   double sum2 = 0;
   for (double n : numbers) {
      if (n>0.0) {
          sum1 += n;
      } else {
          sum2 += n;
      }
   }
   System.out.println("Sum of positives "+sum1);
   System.out.println("Sum of negatives "+sum2);
}
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Author

Commented:
Is there any other way to do it because I don't know if my teacher will like me using Math.min or Math.max.
Expert of the Quarter 2010
Expert of the Year 2010

Commented:
Because this is obviously a learning exercise, I will make some explanations, otherwise we would be unethically helping you to cheat.  If you can understand it (and therefore reproduce), then it is a different thing.

Good thing you already have code, so I can tell you where you went wrong.  Hopefully that will give you some insight.

Read here on using the iterator in a for-each loop.
http://download.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Your while loop is ok, but more commonly used is for( ; ; ) or for ( : ).  Not sure which one you have been taught.  The for( : ) for is more elegant, although it is useful to learn the for( ; ; ) form for general use and also if multiple iterators need to be used in sync; can't with for( : ).
        System.out.println("Positive Numbers");

        while (it.hasNext()) {
            number = it.next();   /// HERE we retrieve one number (a) from iterator
            sum = sum + it.next();   /// WHAT GIVES, we take another number (b)
                                    /// At this point, we took (a) and it has gone to the ether
        }

        System.out.println(sum);
        // }
        System.out.println("Negative Numbers");

//// You forgot to reset "sum" here.  It is carrying forward the previous sum
        while(it.hasNext()) {    /// WE have reached the end of Iterator "it" using previous loop.
                                /// the condition will never be true and this loop won't happen
            number = it.next();
            sum = sum + it.next();   // same issue, 1 number taken, discarded, another taken
            {
                System.out.println(sum);  // Why is this in the loop?
                                        /// It is printed for each pass through this loop
            }
        }

============================================

Open in new window

Author

Commented:
Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial