Loops
Arrays
2D arrays (matrices)
Looping through arrays
Summary
Quiz
static void main (String[] arguments) {
print("Car #1");
print("Car #2");
print("Car #3");
} What if we had 200 cars?
(get it?)
static void main (String[] arguments) {
int i = 1;
while(i <= 200) {
print("Car #" + i);
i++;
}
} Counting with care
Make sure your loop will finish
while(CONDITION) {
STATEMENTS;
}
static void main (String[] arguments) {
for(int i = 1; i <= 200; i++) {
print("Car #" + i);
}
}
for(INITIALIZATION; CONDITION; UPDATE;) {
STATEMENTS;
}When you know the number of loops
public static void main (String[] args) {
for(int i = 1; i <= 200; i++) {
if(i == 10) {
break;
}
print("Car #" + i);
}
}break terminates the loop
public static void main (String[] args) {
for(int i = 1; i <= 200; i++) {
if(i == 10) {
continue;
}
print("Car #" + i);
}
}continue skips an iteration
public static void main (String[] args) {
String car1 = "Nissan Micra";
String car2 = "Peugeot 206";
String car3 = "Smart for two";
print(car1);
print(car2);
print(car3);
}To create array of given size use the operator new
public static void main (String[] args) {
String[] cars = new String[5];
print(cars);
}Curly braces can be used to initialize an array.
ONLY when you declare the variable!
public static void main (String[] args) {
String[] cars = {"Nissan Micra", "Peugeot 206"};
print(cars);
}Access an element from array using the [ ] operator
public static void main (String[] args) {
String[] cars = {"Nissan Micra", "Peugeot 206"};
print(cars[0]);
}What happens when we try to access cars[2] ?
Each array has a built-in length variable that contains the size of the array
public static void main (String[] args) {
String[] cars = {"Nissan Micra", "Peugeot 206"};
print(cars.length);
}Grid of rows and columns
public static void main (String[] args) {
String[][] cars = {
{"Micra", "350Z", "Primera"},
{"206", "306", "406"}};
print(cars);
// Alternative
String[][] cars1 = new String[2][3];
cars1[0][0] = "Micra";
}Initialize
Another
way
Or how to combine arrays and loops
public static void main (String[] args) {
String[] cars = {"Nissan Micra", "Peugeot 206"};
for(int i = 0; i < cars.length; i++) {
print(cars[i]);
}
}http://wp.me/P67zDd-19