• No results found

Enhanced For Loop (for each loop)

N/A
N/A
Protected

Academic year: 2021

Share "Enhanced For Loop (for each loop)"

Copied!
10
0
0

Loading.... (view fulltext now)

Full text

(1)

Enhanced For Loop (for each loop)

The enhanced for loop allows you to iterate through a collection without having to create an Iterator or without having to calculate beginning and end conditions for a counter variable. So what does an enhanced for loop look like? Suppose you have an ArrayList of String objects called wordList. You could use an enhanced for loop with the collection as follows:

for (String word : wordList) // wordlist is an ArrayList of type String <do something with word>

You read this as "for each word in wordlist”. Here the variable word is used to point to the current instance of String in the collection. Because of the "for each" wording, the enhanced-for construct is also referred to as the for-each construct.

If you compare the enhanced for loop to the typical way of iterating over a collection, it's clear that the for each loop is simpler and can make your code more readable.

Also note that the enhanced for loop is designed to simplify your work with generics.

The enhanced for loop works with arrays as well as any data type that implements the Iterable interface.

for ( Type Identifier : Expression ) Statement

Expression must be an instance of an array or any type that implements Iterable.

For example, the following program segment would output all the elements of an array using an Enhanced For Statement.

int[] list = new int[10];

for (int item: list) // list is the array. Item is the next element in the array System.out.println(item);

(2)

2

Lab 07A - 60 points

OBJECTIVE

WAP that reads a series of integer values from a data file (“lab07a.dat”) and stores them in an ArrayList of type Integer. Display the sorted contents of the list, the sum, and the average of all the numbers in the list. Then output the smallest and largest numbers in the list.

FIELD SUMMARY ArrayList<Integer> list – a list of integer values.

METHOD SUMMARY

main – instantiate an object of this class. Make method calls to input and output.

input – declare a Scanner object and read a series of integer values from a data file storing them in list.

sum – Arguments: an ArrayList of type Integer. Return: the sum of all the numbers in the argument in the form of an int. This method should be declared as static.

average – Arguments: an ArrayList of type Integer. Return: the average of all the numbers in the argument in the form of a double. This method should make a call to sum. This method should be declared as static.

output – sort and display all the numbers in list, the sum of all the numbers, the average of all the numbers, and the smallest and largest values in list.

SAMPLE OUTPUT The sorted list:

1 2 3 4 7 8 10 13 14 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 35 39 41 43 44 46 47 48 49 52 53 54 55 57 58 59 60 62 65 68 69 70 71

The sum of all the numbers is 1666 The average of all the numbers is 35.45 The smallest value is 1

(3)

3

Lab 07B - 70 points

OBJECTIVE 1

WAC called Presidents that stores the name, year born, and party affiliation for U.S. Presidents. The name and party affiliation should be stored as Strings and the year born should be stored as an integer. Read Presidents.pdf for a detailed list of constructors and methods that must be implemented in the President class.

Double click on PresidentTester.bat to test your President class. SAMPLE OUTPUT

Presidents of the United States: 1. 1732 - George Washington 2. 1735 - John Adams

3. 1743 - Thomas Jefferson 4. 1751 - James Madison 5. 1758 - James Monroe 6. 1767 - John Quincy Adams 7. 1767 - Andrew Jackson

(4)

4

32. 1884 - Harry S. Truman 33. 1890 - Dwight D. Eisenhower 34. 1908 - Lyndon B. Johnson 35. 1911 - Ronald Regan 36. 1913 - Richard Nixon 37. 1913 - Gerald Ford 38. 1917 - John F. Kennedy 39. 1924 - Jimmy Carter 40. 1924 - George H. W. Bush 41. 1946 - Bill Clinton 42. 1946 - George W. Bush

43. 1961 - Barack Hussein Obama

Theodore Roosevelt is the 27 President in the list Presidents born in the 20th Century:

Lyndon B. Johnson (1908) Ronald Regan (1911) Richard Nixon (1913) Gerald Ford (1913) John F. Kennedy (1917) Jimmy Carter (1924) George H. W. Bush (1924) Bill Clinton (1946) George W. Bush (1946)

Barack Hussein Obama (1961)

OBJECTIVE 2

WAP that reads the name, year born, and political affiliation of all the U.S. Presidents up until the present time from a data file (“lab07b.dat”). Store the information in an ArrayList of President objects. You will then provide three separate outputs. Read the METHOD SUMMARY for detailed information about each output method.

FIELD SUMMARY ArrayList<President> list – a list of President objects.

METHOD SUMMARY

main – instantiate an object of this class. Make method calls to input and all three output methods.

(5)

5

instances of President objects.

output1 – sort and display all the Presidents whose name begins with “James”. Remember, the String class contains a startsWith method. You must traverse the list using an Iterator. output2 – display all the Presidents born in the 19th

Century. In other words, Presidents born in the 1800’s. You must traverse the list using a standard for loop.

output3 – display all the Presidents that were members of the Republican Party. You must traverse the list using an enhanced for loop.

SAMPLE OUTPUT Presidents with the first name of James:

1751 - James Madison 1758 - James Monroe 1791 - James Buchanan 1795 - James K. Polk 1831 - James A. Garfield

(6)
(7)

7

Lab 07C - 80 points

OBJECTIVE

Vector graphics is the use of geometrical primitives such as points, lines, curves, and shapes or polygon(s), which are all based upon mathematical equations, to represent images in computer graphics. Since vector drawn images are equations then each image can be represented by a class that holds information about the shape, color, and location (coordinates). You have been provided with an interface, DrawingShape, that represents vector images. The DrawingShape interface provides two methods:

Method Summary

– DrawingShape

abstract

void drawShape(Graphics g) Renders this drawing shape on the Graphics context g.

void isMouseOver(int x, int y)

Returns true if this DrawingShape contains the coordinates x, y. Open the file MyVectorDraw.java and complete the method findShape.

public DrawingShape findShape(ArrayList<DrawingShape> shapes, Point loc)

(8)

8

Lab 07D - 100 points

OBJECTIVE 1

WAC called MenuItem that stores information about menu items sold in a resturant. MenuItem will store the category of the item, the name of the item, a description of the item, and the prices. A MenuItem is a Comparable object. Equality is based on the category and then on the name.

Double click on MenuItemTester.bat to test your MenuItem class. FIELD SUMMARY

String category – the category this menu item falls under, i.e. appetizer, entree, etc.. String name – the name of this menu item, i.e. BBQ Chicken.

 String description - a description of this menu item, i.e. Tasty and delicious.  double price – the price associated with this menu item, i.e. 9.99.

METHOD SUMMARY

A constructor that receives arguments for all four instance fields, accessors for each instance field, equals (equality is based on the menu item name), and toString which should return the name, description, and price of the item. Since MenuItem is comparable a compareTo method is required.

SAMPLE OUTPUT Category: appetizer

-Boneless Buffalo Wings - Hand-breaded all white meat chicken tossed in your cho ice of Mild or Hot sauce and served with celery and Bleu Cheese dressing - 7.99 -Combo Appetizer - Boneless Buffalo Wings (tossed in your choice of Mild or Hot sauce) along with Rattlesnake Bites and Tater Skins served with your choice of t wo dipping sauces - 9.99

-Fried Pickles - Basket of pickle chips hand-battered, golden-fried and served w ith Ranch or Cajun Horseradish sauce for dipping - 4.99

-Grilled Shrimp - Skewer of shrimp, seasoned to perfection and drizzled with our garlic lemon pepper butter - 5.99

-Rattlesnake Bites - Diced jalape±os and jack cheese, hand-battered, lightly-fri ed and served with Cajun Horseradish sauce - 4.99

-Tater Skins - Topped with cheddar cheese, bacon and sour cream - 5.99 Category: dessert

-Big OlÆ Brownie - 5.99

(9)

9

Category: entree

-All-American Cheeseburger - Our classic with American cheese - 8.49

-BBQ Chicken - Marinated and grilled, then basted with BBQ sauce and served with lettice, tomato and onion - 8.0

-Bacon Cheeseburger - Bacon strips and American cheese - 8.99

-Bone-In Ribeye - Our most flavorful steak, hand-cut to perfection 20 oz. - 23.9 9

-Fall-Off-The-Bone Ribs - Our award winning ribs are slow cooked with a unique b lend of seasonings and our signature BBQ sauce. - 12.99

-Filet Medallions - Three tender filets (9 oz total) topped with Peppercorn or P ortobello Mushroom sauce - 18.99

-Mushroom Jack Chicken - Fresh chicken breast with sauteed mushrooms, melted jac k cheese and served with lettuce, tomato and onion - 9.49

-Porterhouse T-Bone - 23oz. Texas-sized USDA Choice cut - 26.99

-Pulled Pork - Tender, slow cooked pork covered in our signature BBQ sauce - 8.4 9

-Road Kill - 10 oz. chop steak smothered with sautΘed onions, sautΘed mushrooms and jack cheese - 9.99

-Smokehouse Burger - Sauteed mushrooms, onions and BBQ sauce with American and j ack cheeses - 9.49

-Steak Kabob - Marinated steak with onion, mushroom, tomato, red pepper and gree n pepper served on a bed of seasoned rice with choice of one side - 10.99

Category: salad

-Chicken Caesar Salad - Tender strips of grilled chicken tossed with crisp heart s of romaine, fresh parmesan cheese, made-from-scratch croutons and our zesty Ca esar dressing - 9.99

-Chicken Critter Salad - Hot crispy strips of chicken piled high on a bed of col d greens with jack and cheddar cheeses, egg, tomato and bacon - 9.99

-Grilled Chicken Salad - Crisp cold greens, strips of marinated chicken, jack ch eese, egg, tomato, bacon, red onions and croutons - 9.99

-House Salad - Fresh greens, cheddar cheese, tomato, eggs and made-from-scratch croutons - 3.99

-Steakhouse Filet Salad - Salad greens drizzled with Italian dressing, topped wi th tender filet strips, Bleu Cheese crumbles, bacon bits, red onions, tomatoes a nd croutons, and served with a side of creamy Bleu Cheese - 12.99

OBJECTIVE 2

(10)

10

FIELD SUMMARY ArrayList<MenuItem> menu – a list of MenuItems. ArrayList<String> order – a list of names of menu items.

METHOD SUMMARY

main – instantiate an object of this class. Make method calls to menuInput, orderInput, and then call output.

menuInput – declare a Scanner object and read the menu items from the data file <menu.dat> storing them in the ArrayList menu.

orderInput – declare a Scanner object and read the order from the data file <order.dat> storing them in the ArrayList order.

output – display all the items in the order by name and price. Then calculate and display the subtotal, tax, and balance due.

getPrice – This method should be static and should return a double. It should receive an ArrayList of type MenuItem and a String representing a menu item. This method should locate menu item in the ArrayList and return the price of item.

getTotalPrice – This method should be static and should return a double. It should receive an ArrayList of type MenuItem and an ArrayList of type String representing an order This method should calculate and return the total price of the order by calling getPrice for each item in the order.

References

Related documents

The file is opened using the fopen function, but this time the file mode is set to “rb” which indicates that a binary file will be read from disk.. Next, a loop is created which

$ ./a.out &lt;in.dat &gt;out.dat scanf() will read data inputs from the file.. “in.dat”, and printf() will output results on the file “

Blue cheese potato croquettes, braised carrot, alliums Braised shoulder of lamb. Sweet potato, tender steam broccoli, pea puree, cumin Ras al hanout

The Artist Village serves as a creative hub for artists, students, business owners, and neighbors living and working in the heart of Old Redford. A once abandoned commercial

Property Insurance policies must specify exactly which property loss exposures are covered – that is, the types and locations of property, cause of loss, and financial

To open the Import file dialog box, click the Import media file(s) command from the main menu or from the shortcut menu that is opened with right-click in the file list panel. When

To export this data into a file that can be read by another application (e.g. Microsoft Word or Excel), select a file format from the Export File type dropdown list and click

To open an existing data file for viewing on the data graph window, click on the FILE OPEN icon on the menu bar (3 rd from left) or select FILE OPEN from the FILE pull-down