Skip to content

Flow Control Exercise

Estimated time to read: 5 minutes

Using Java Flow control

Create a new class named Lab3. Ensure that the new Lab3 class has a main() method.

Exercise 1: 'for' loop

package io.entityfour.exercises.coursera;

public class Lab3 {

    public static void main(String[] args) {

 // Create an array of String references named daysOfWeek and initialise it with the names of the days of the week starting with Sunday.
    String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    //
    // Write a for loop to print out each element of the array. 
    //

    // Do this two ways – the first using the standard for loop
    //                    the second using the for-next construct.

 // Standard For loop
        // Create an int, i, for us to count with
        // Compare i against the length of the array
        // Run the code block
        // Apply the post block content, add 1 to i
 for (int i = 0; i < daysOfWeek.length; i++){
  System.out.println(daysOfWeek[i]);
 }

    // For-Next loop
        // Ha no, these are out dated. Everyone just uses for loops these days

    // Write another for loop to print out each element of the array in reverse. 
    // Note that the only way this can be done is by using the standard for loop.
        // Get array length, minus 1 becaues arrays start at 0
        // If i is greater than 0, run the code
        // Take 1 off of i
    for (int i = daysOfWeek.length - 1 ; i > 0; i--) {
        System.out.println(daysOfWeek[i]);
    }
    }
}

Exercise 2: 'while' loop

package io.entityfour.exercises.coursera;

public class Lab3_2 {

    public static void main(String[] args) {

    // Create a while loop that will print out only even numbers between 1 and 20.
        // Create an int with a value of 0
    int i = 0;
        // Create a while loop that evaluates i++ less than 20. The postfix is run after the evaluration remember!
    while (i++ < 20){
        // Print out a new line with the value of i
        System.out.println(i);
    }


    // // Use the continue statement and an if statement to skip printing the odd numbers (i.e. increment the counter by 1 each time through the loop).
    //     // Create an int with a value of 0
    // i = 0;
    //     // Create a while loop that evaluates i++ less than 20. The postfix is run after the evaluration remember!
    // while (i++ < 20){
    //     // If i is divisible by 2 and leaves no remainder, it must be even.
    //     if (i % 2 == 0){
    //         System.out.println(i);
    //     }
    // }

    // Theres a better way to do this I think...
        // Create an int with a value of 0
    i = 0;

        // i & 1 produces a value that is either 1 or 0, depending on the least significant bit of i: 
        // If the last bit is 1, the result of i & 1 is 1; otherwise, it is 0. 
        // This is a bitwise AND operation.
        // All odd numbers have a least significant (last) bit of 1
        // All even numbers have a least significant (last) bit of 0

        // It is not readable though :S But neat at least.
    while (i++ < 20){
        if ( (i & 1) == 0 ) {
            System.out.println(i);
        }
    }
    }
}

Exercise 3 - for loop

package io.entityfour.exercises.coursera;

public class Lab3_3 {

    public static void main(String[] args) {
        //Create a for loop that will print out all numbers between 1 and 100 except 50 thru 60.
        for (int i = 1; i < 100; i++){
            if (i < 50) {
                System.out.println(i);
            }
            else if (i > 60) {
                System.out.println(i);
            }
        }
    }
}

Exercise 4 - switch statement

This is how not to do this

package io.entityfour.exercises.coursera;

public class Lab3_4 {
    public static void main(String[] args) {
        String[] monthNames = {"January", "February", "March", "April", "May","June","July","August","September","October","November","December"}; // Declare an array with string values
        int[] daysInMonths = new int[12];

        daysInMonths[0] = 31;
        daysInMonths[1] = 28;
        daysInMonths[2] = 31;
        daysInMonths[3] = 30;
        daysInMonths[4] = 31;
        daysInMonths[5] = 30;
        daysInMonths[6] = 31;
        daysInMonths[7] = 31;
        daysInMonths[8] = 30;
        daysInMonths[9] = 31;
        daysInMonths[10] = 30;
        daysInMonths[11] = 31;

        int i = 1;
        while (i <= 12) {
            switch (i) {
                default:
                    System.out.println(monthNames[i-1] + " has " + daysInMonths[i-1] + " days.");
                    i++;
            }

        }

    }
}

This is a bit better

package io.entityfour.exercises.coursera;

public class Lab3_4 {
    public static void main(String[] args) {
        // Create a while loop that will execute the following code 12 times using a counter that starts at 1 and is incremented by 1 each time through the loop.
        int i = 1;
        while (i > 12);
            // Within the while loop, create a switch statement that will print out the number of days in each of the months of the year.
            switch (i) {
                case 1:
                    System.out.print("January ");
                case 3:
                    System.out.print("March ");
                case 5:
                    System.out.print("May ");
                case 7:
                    System.out.print("July ");
                case 8:
                    System.out.print("August ");
                case 10:
                    System.out.print("October ");
                case 12:
                    System.out.print("December ");
                    System.out.println("have 31 days.");
                case 4:
                    System.out.print("April ");
                case 6:
                    System.out.print("June ");
                case 9:
                    System.out.print("September ");
                case 11:
                    System.out.print("November ");
                    System.out.println("have 30 days.");

                case 2:
                    System.out.print("February ");
                    System.out.println("have 28 days.");
            }
        }
    }

Challenge Exercise

This is good enough for now. It works, but it is hard coded to work. If you change the startDay, it breaks!

package io.entityfour.exercises.coursera;

public class Lab3_5 {
    public static void main(String[] args) {
        System.out.println("Start of output for Challenge Exercise");

        // String array with days of the week
        String[] daysOfWeek = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        // Int with count of days in month
        int daysInMonth = 31;
        int startDate = 1;
        // Starting Day
        int startingDay = 5;
        // Print the days of the week array to the console
        for (String da : daysOfWeek) {
            System.out.print(da);
            System.out.print("\t");
        }
        System.out.println("\t");

        // Create the dates in the calendar
        // For each line count in rowCount, make a row of columns based upon the count of columnCount


        for (int rowCount = 5; rowCount > 0; rowCount--) {

            int columnCount = 6;
            if (rowCount == 5) {
                do  {
                    System.out.print("\t");
                    --startingDay;
                } while ( startingDay > 0);
                columnCount = startingDay + 1;
            }


            for (columnCount++; columnCount > 0; columnCount--) {

                if (startDate < daysInMonth){
                    System.out.print(startDate++);
                    System.out.print("\t"); // The usage of a '\t' here is neat. It is an escaped 'tab', better than using spaces.
                }
            }
            System.out.println("");
        }

    }
}


// Create the necessary variables, loops and flow control to print March as a calendar. The calendar will have:
    // a. A heading with the days of the week
    // b. 5 rows with the days of the month in the correct column
    // c. Assume that March 1 starts on a Friday
    // d. Each week on the calendar should flow from Sunday – Saturday (left to right).
    // e. You can use the function System.out.print() to print information to the console without adding a carriage return.