Page 454 - Introduction to Programming with Java: A Problem Solving Approach
P. 454
420 Chapter 10 Arrays and ArrayLists
//*******************************************************
// Prompt user for bear's maker and type and return bear.
private Bear getUserSpecifiedBear()
{
Scanner stdIn = new Scanner(System.in);
String maker, type;
System.out.print("Enter bear's maker: ");
maker = stdIn.nextLine();
System.out.print("Enter bear's type: ");
type = stdIn.nextLine();
return new Bear(maker, type);
// end getUserSpecifiedBear
//*******************************************************
anonymous object as return value
}
// Print all the bears in the store.
public void displayInventory()
{
for (Bear bear : bears) ⎫ Apago⎪
{
⎬ bear.display(); ⎪
}⎭ // end displayInventory
PDF Enhancer
for-each loop
}
// end BearStore class
}
//*******************************************************
public static void main(String[] args)
{
}
BearStore store = new BearStore();
store.addStdBears(3);
store.addUserSpecifiedBears(2);
store.displayInventory();
// end main
Figure 10.29b Class that implements a toy-bear store—part B Embedded Driver
At the bottom of the BearStore class, we’ve embedded the program’s driver, main. It instantiates a BearStore object, adds three standard bears to the bear store, adds two user-specified bears to the bear store, and then displays the store’s inventory of bears by calling displayInventory. In displaying the store’s inventory, the displayInventory method accesses each bear in the bears ArrayList with the help of a for-each loop. In the next subsection, you’ll learn about for-each loop details.