• Final Hack
  • Enhanced For Loop (For-each)

    An enhanced For Loop is a simplified version of a regular for loop, where the coder doesn’t need to specify the increment and can access each element directly.

    Pros

    • Can access the elements of a array instad of a counter
    • Enhanced readability
    • Less likely to be buggy

    Cons

    • Can only traverse the array in order
    • Accesses a copy of the array, so modifications to the variables are not saved in the original array

    Regular For Loop

    Regular For Loop

    Enhanced For Loop

    Enhanced For Loop

    int[] numbers = {10, 20, 30, 40, 50};
    for (int number : numbers) {
        number += 1;
        System.out.println(number);
    };
    
    System.out.println(Arrays.toString(numbers))
    

    Comparing a regular for loop with the enhanced for loop

    Popcorn Hack: Rewrite this code to use an enhanced for loop instead. make comments explaining what you added/changed

    String[] languages = {"Java", "Python", "Markdown", "C++", "Go", "JavaScript", "HTML"};
    
    for (int i = 0; i<languages.length; i++) {
        System.out.println(languages[i]);
    };
    

    Hacks

    1. Build the loop
    2. Multiple Choice
    3. Find each index of the letter ‘a’ in each word
    4. Find the error
    5. HW Hack
    String[] myArray = {'Add an array here'};
    
    // Add a loop to go through the array here
    
    private String[] myArray = {
        "And", "Table", "Shirts", "Tea", "School Day"
    };
    
    for (String currentWord : myArray) {
        // Add code here
    }
    
    A: System.out.println(myArray.currentWord.length());
    B: System.out.println(myArray[index].length());
    C: System.out.println(myArray[currentWord].length());
    D: System.out.println(currentWord.length());
    
    String[] fruits = {"Apple", "Banana", "Orange"};
    
    for (String fruit: fruits) {
        // Find the index of the letter 'a' in each fruit
    };
    
    String[] myArray = {"Object 1", "Object 2", "Object 3", "Object 4", "Object 5"};
    
    for (currentWord: myArray) {
        System.out(currentWord)
    };
    
    // There are 3 errors, can you find them?
    

    Final Hack

    Add to the code below to create a average grade calculator (using an enhanced for loop)

    Integer[] grades = {88, 93, 55, 68, 77};
    
    Scanner userGrades = new Scanner(System.in);
    System.out.print("Enter a grade: ");
    int grade = Integer.parseInt(userGrades.nextLine());
    
    // Add code here to take the average
    
    grades = Arrays.copyOf(grades, grades.length + 1);
    grades[grades.length - 1] = grade;
    System.out.println(Arrays.toString(grades));