跳转至

Lecture3 Loops, Arrays

1. Good programming style

The goal of good style is to make your code more readable, by you and by others.

  • Use meaningful names
  • Use indentation
  • Use whitespaces
  • Do not duplicate tests

2. Loops

Lecture3 Loops, Arrays-1790675320997.webp

Loop operators allow to loop through a block of code.

Java
// while loops
while (condetion) {
    statements
}

// Make sure that your loop has a chance to finish

// for operator
for (initialization; condition; update){
    statements
}

for (int = 0; i < 3; i += 1) {
    System.out.println("Rule #" + i);
}

//branching statements break and continue, the same as python

3. Arrays

An array is an indexed list of values and all elements of an array must have the same type.

The index starts at zero and ends at length-1

Java
int[] values = new int[5]; // To create an array of given size, use the operator new

// Array initialization
int[] values = {12, 24, -24, 47}; // It can ONLY be used when you declare the cariable

//Accessing Arrays
values[index]

//The length variable
values.length

//String Arrays
public static void main (String[] arguments){ 
    System.out.println(arguments.length); 
    System.out.println(arguments[0]); 
    System.out.println(arguments[1]); 
}

//Combining loops and arrays

Assignment3 Marathon

Java
class Marathon {
    public static void main (String[] arguments) {
        String[] names = {
            "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
            "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
            "Aaron", "Kate"
        };

        int[] times = {
            341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
            343, 317, 265
        };

        int best_i = 0;

        for (int i = 0; i < names.length; i++) {
            if (times[i] > times[best_i]) {
                best_i = i;
            }
        }

        System.out.println("Best runner: " + names[best_i]);
        System.out.println("Time: " + times[best_i]);
    }
}