Friday, June 10, 2011

For-Each Loop Java

import java.util.ArrayList;

public class ForEach {
 
 static void array(){
 
  double[] array = {9.5, 4.3, 3.8, 8.8};
  double sum = 0;
  
  for (double d : array) {  
   sum += d;
  } 
  
  System.out.println(sum);
  
 }
 
 static void arrayList(){
  
  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  arrayList.add(1);
  arrayList.add(2);
  arrayList.add(3);
  arrayList.add(4);
  arrayList.add(5);
  
   for (int integer : arrayList)
        System.out.print(integer + " ");
 }
 
 public static void main(String args[]){
  
 array();
 arrayList();
  
 }
 
}

I will be updating this post to show how to use for-each loop with other datastructures.

No comments:

Post a Comment