How do I turn this for loop into a for each loop?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mary Seelye
    New Member
    • Oct 2010
    • 14

    #1

    How do I turn this for loop into a for each loop?

    Code:
    public void increaseVolume2()
      {
        SoundSample[] sampleArray = this.getSamples();
        SoundSample sample = null;
        int value = 0;
       
        //loop through all the samples in the array
        for (int i = 0; i < sampleArray.length; i++)
        {
          sample = sampleArray[i];
          value = sample.getValue();
          sample.setValue((int) (value * 2));
        
        }
      }
    Last edited by gits; Oct 30 '10, 09:03 AM. Reason: added code tags
  • Monomachus
    Recognized Expert New Member
    • Apr 2008
    • 127

    #2
    Well I found using google this link:
    Using Foreach Loops in J2SE 1.5

    So you need to implement Iterable interface and create an Iterator method for your class. In your case it should be SoundSample.
    Code:
    class Catalog implements Iterable<Product> {
       private List<Product> products = new ArrayList<Product>();
       void add(Product product) {
          products.add(product);
       }
       
       public Iterator<Product> iterator() {
          return products.iterator();
       }
    }
    
    Catalog catalog = new Catalog();
    
    catalog.add(new Product("1", "pinto", new BigDecimal("4.99")));
    catalog.add(new Product("2", "flounder", new BigDecimal("64.88")));
    catalog.add(new Product("2", "cucumber", new BigDecimal("2.01")));
    
    for (Product product: catalog)
       product.discount(new BigDecimal("0.1"));
       
    for (Product product: catalog)
       System.out.println(product);

    Comment

    • Mary Seelye
      New Member
      • Oct 2010
      • 14

      #3
      I'm not quite sure what you're doing here.
      I need it to stay as close to what I have as possible.

      Comment

      • Mary Seelye
        New Member
        • Oct 2010
        • 14

        #4
        I think I figured it out.

        This is what I have now and it works just fine:
        Code:
        public void increaseVolume3()
          {
            SoundSample[] sampleArray = this.getSamples();
            int value = 0;
           
            //loop through all the samples in the array
               for (SoundSample sample : sampleArray)
            {
              
              value = sample.getValue();
              sample.setValue((int) (value * 2));
            
            }
          }
        Last edited by gits; Oct 30 '10, 09:03 AM. Reason: added code tags

        Comment

        Working...