Could someone please explain what the for loop in this class does? Specifically the part with (String person : people)
import java.util.Scanner;
/**
* This program uses the startsWith method to search using
* a partial string
*
*
*/
public class PersonSearch {
public static void main(String[] args){
String lookUp; //To hold a lookup string
//Create an array of names
String[] people= {"Cutshaw, Will", "Davis, George",
"Davis, Jenny", "Russert, Phil",
"Russel, Cindy", "Setzer, Charles",
"Smathers, Holly", "Smith, Chris",
"Smith, Brad", "Williams, Jean" };
//Create a Scanner object for keyboard input
Scanner keyboard=new Scanner(System.in);
//Get a partial name to search for
System.out.println("Enter the first few characters of "+
"the last name to look up: ");
lookUp=keyboard.nextLine();
//Display all of the names that begin with the
//string entered by the user
System.out.println("Here are the names that match:");
for(String person : people){
if (person.startsWith(lookUp))
System.out.println(person);
}
}
}
Thank you.
It's called the foreach syntax. It works with arrays and Objects that implement Iterable.
For arrays (as here) it's equivalent to this code:
for (int i = 0; i < people.length; i++) {
person = people[i];
// code inside loop
}
For Iterable<T> iterable (eg a List), it's equivalent to:
for (Iterator<T> i = iterable.iterator(); i.hasNext(); ) {
T next = i.next();
// code inside loop
}
This code pattern was so common, and added so little value, this abbreviated form of looping was officially made part of the java language in version 1.5 (aka "Java 5").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With