Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9for Loop and Lists9-24-2010Opening Discussion●Do you have any questions about the quiz?●Minute Essay comments–I want you to be more creative in your ideas.–Common errors and fixes to save heads and walls.–Can you use the Wombat “walk”?–Rockets blowing up houses.–Meaning of null and exceptions.–Complexity of code.Objectives for the Week●The first objective is to be able to repeat code without doing cut and paste.●We want to use this to have the people walk toward the closest house.●Then we want to make it so each house can only hold one person.Repeating Code●So far, if I have asked you to do something several times you have just copied the code.●This is inefficient and inflexible. Can't do it a variable number of times.●Let's consider a new method in city: –void addBuildings(int howMany)●Copy and paste can't do this.●The solution is a construct called a loop.The for Loop●The first loop we will learn about is the for loop. These are the most commonly used loops in Java and can do anything you want.–for(init; condition; iterator) {...}●We will start off with just counting.–for(int i=0; i<number; i++) {...}●The variable doesn't have to be i.●The statement i++ is shorthand for i=i+1.●Now let's add the buildings.Lists●Right now one variable refers to one object. We want to be able to deal with collections of objects.●The Greenfoot API has methods in World that tell us about Actors. These all return lists. Let's look at them.●We can also look at List in the full API. The main methods we need now are get(int index) and size().●List indexes start at zero.Generics●The List class is a generic class. Because of this, we tell it what type it works with.●The syntax for this is to put the type the list will hold inside of angle braces after the word List.●In our case we want a list of houses.–List<House>House Hunting●Let's work on a method in our person called findNearestHouse().●First, we should see if we can figure out how to run through all the buildings.●Once we can do that we need to figure out how to determine which one is closest.Minute Essay●What questions do you have about the things that we covered today? How comfortable do you feel working in
View Full Document