// File: ElementaryListTester.java // The ElementaryList class has an instance variable that is an int array // object variable. The constructor takes one parameter: the size (i.e., // number of elements) of the int array object to be created. The class // methods show how to use a for statement to "traverse" an array (i.e., to // "visit" each element). import java.util.Arrays ; import javax.swing.JOptionPane ; /** * A class to help students learn about arrays. */ class ElementaryList { // instance vars private int [] list ; // an int array object variable /** * Creates a ElementaryList object with an array of a specified size. * @param size the number of elements of the array object to be created */ public ElementaryList(int size) { list = new int [size] ; } /** * Fill the array with successive powers of 2, beginning with 1 */ public void fill() { for (int i = 0 ; i < list.length ; i++) { list[i] = (int)Math.pow(2,i) ; } } /** * Print the elements of the array in order, from 1st to last */ public void print() { for (int i = 0 ; i < list.length ; i++) { System.out.print( list[i] + " " ) ; } System.out.println() ; } /** * Print the elements of the array in reverse order, from last to 1st */ public void printReversed() { for (int i = list.length - 1 ; i >= 0 ; i--) { System.out.print( list[i] + " " ) ; } System.out.println() ; } } public class ElementaryListTester { public static void main (String [] args) { String input = JOptionPane.showInputDialog ("How many powers of 2 do you want to see?") ; int number = Integer.parseInt(input) ; ElementaryList myList = new ElementaryList(number) ; myList.fill(); System.out.println("\nThe first " + number + " powers of 2:\n") ; myList.print() ; System.out.println("\nHere they are again, in reverse order:\n") ; myList.printReversed() ; System.exit(0) ; } } /* sample output: The first 13 powers of 2: 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 Here they are again, in reverse order: 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 */