/* * @topic T01205 Array Reference Demo II * @brief Array initialization, standard "for" and enhanced "foreach" loop examples */ package pckg; /* Demo program for standard for loops * and enhanced for loops (aka foreach loops) * using arrays of primitives and ArrayList objects. * * (1) Note that it uses a standard for loop with an array that is * is full and then it uses an enhanced for loop with array that * is not full. In each case it is obvious that it is using the * length attribute of the array object to halt processing. * * (2) Note that it then uses a standard for loop with an ArrayList * that has three String objects, and later after two more String * objects have been added, it uses an enhanced for loop to display * the objects. In each case it is obvious that it is using the * result of calling the size method to halt processing. */ import java.util.ArrayList; public class EnhancedForLoops { public static void main(String args []) { System.out.println("Array output using a standard for loop and.length"); double [] prices = {29.95, 12.89, 34.56, 78.23}; for(int i = 0; i < prices.length; i++) { System.out.println(prices[i]); } System.out.println("Array output using an enhanced for loop and .length"); double [] sales = new double [4]; sales[0] = 45.67; sales[1] = 34.94; for(double sale : sales) { System.out.println(sale); } System.out.println(); //******************************************************************* ArrayList<String> codes = new ArrayList<String>(); codes.add("cis73"); codes.add("cis74"); codes.add("cis75"); System.out.println("ArrayList output using a standard for loop and size()"); for(int i = 0; i < codes.size(); i++) { String code = codes.get(i); System.out.println(code); } codes.add("cis76"); codes.add("cis77"); System.out.println("ArrayList output using an enhanced for loop and size()"); for(String code : codes) { System.out.println(code); } } } /* Array output using a standard for loop and.length 29.95 12.89 34.56 78.23 Array output using an enhanced for loop and .length 45.67 34.94 0.0 0.0 ArrayList output using a standard for loop and size() cis73 cis74 cis75 ArrayList output using an enhanced for loop and size() cis73 cis74 cis75 cis76 cis77 Press any key to continue... */