Java: Combining Traversal and Conditional Logic

Traversals with Conditional Logic:

Welcome to Combining Traversal and Conditional Logic in Java. Let’s begin!

It’s important to be able to combine traversal logic with conditional logic when working with 2D arrays in order to navigate and process the data effectively. Conditional logic can affect 2D array traversal in a number of ways:

  • We can skip or select rows and columns.
  • Only modifying elements if they meet certain criteria
  • Using 2D array data to perform complex calculations
  • The 2D array is formatted.
  • Exception avoidance / intelligent processing

Let’s look at a few examples of how these concepts are used:

For Example, you have some string data stored in a 2D array. We have a calendar application that allows users to enter events. A 5×7 2D array of strings represents this. We know that some of our elements will be empty due to the fact that the number of days in each month varies slightly and that there are less than 35 days in a month. We want our app to be able to do the following:

  • Determine which days of which weeks have something planned and notify us.
  • Count how many events each week has.
  • Count how many events there are on each day.

Here’s a visual representation of our calendar data after a user has entered some event details:

This is how our calendar data appears in our application.

String[][] calendar = {{"volunteer", "delivery", null, null, "doctor", null, "soccer"}, {null, "exam 1", null, "mechanic", null, null, "soccer"}, {"volunteer", "off work", null, "birthday", null, "concert", null}, {null, "exam 2", null, null, "doctor", null, "soccer"}, {"visit family", null, null, null, null, null, null}};

Let’s look at some code that fulfills the requirements above. Carefully look through each line of code and read all of the comments.

Furthermore, There are a couple of things to keep in mind:

  • We can access individual events by row-major or column-major order.
  • Because each row represents a week, we must count the number of events per in row-major order.

Now, let’s take care of the first 2 requirements in one set of nested row-major loops

for(int i = 0; i < cal.length; i++) {
   int numberOfEventsPerWeek = 0;
    for(int k = 0; k < cal[i].length; k++) {
        // We need conditional logic to ensure that we do not count the empty days
        String event = cal[i][k];
        if(event!=null && !event.equals("")) {
            // If the day does not have a null value or empty string for an event, then we print it and count it
            System.out.println("Week # " + (i+1) + ": Day: " + (k+1) + ": Event: " + event);
            numberOfEventsPerWeek++;
        }
    }
    System.out.println("Total number of events for week "+ (i+1) +": " + numberOfEventsPerWeek + "\n");
}

The output of the above code will be:

Week # 1: Day: 1: Event: volunteer
Week # 1: Day: 2: Event: delivery
Week # 1: Day: 5: Event: doctor
Week # 1: Day: 7: Event: soccer
Total number of events for week 1: 4

Week # 2: Day: 2: Event: exam 1
Week # 2: Day: 4: Event: mechanic
Week # 2: Day: 7: Event: soccer
Total number of events for week 2: 3

Week # 3: Day: 1: Event: volunteer
Week # 3: Day: 2: Event: off work
Week # 3: Day: 4: Event: birthday
Week # 3: Day: 6: Event: concert
Total number of events for week 3: 4

Week # 4: Day: 2: Event: exam 2
Week # 4: Day: 5: Event: doctor
Week # 4: Day: 7: Event: soccer
Total number of events for week 4: 3

Week # 5: Day: 1: Event: visit family
Total number of events for week 5: 1

Third Requirement:

Lastly, let’s finish the third requirement now. We’ll have to traverse the calendar vertically to count all of the events for each of the weekdays.

int numberOfEventsPerWeekday = 0;
// We will use this array of day strings for our output later on so we don't have (day: 1)
String[] days = {"Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"};
for(int i = 0; i < cal[0].length; i++) {
    numberOfEventsPerWeekday = 0;
    for(int j = 0; j < cal.length; j++) {
        // Don't forget to flip the iterators in the accessor since we are flipping the direction we are navigating.
        // Remember, i now controls columns and j now controls rows
        String event = cal[j][i];
        if(event!=null && !event.equals("")) {
            // Make sure we have an event for the day before counting it
            numberOfEventsPerWeekday++;
        }
    }
    // Use the days string array from earlier to convert the day index to a real weekday string
    System.out.println("Number of events on " + days[i] + ": " + numberOfEventsPerWeekday);
}

This example includes a number of previously learned concepts. To ensure that we have data for the elements we are accessing, we use row-major order, column-major order, and conditional logic.

We can also skip sections of the 2D array using conditional logic. Let’s say we only wanted to print the events for the weekdays and not the weekends.

We could use a conditional statement such as if(j!=0 && j!=6) in order to skip Sunday (0) and Saturday (6).

When processing data in applications, these modifications to our 2D array traversal are very common. Furthermore, we need to know which cells to look at (for example, column titles), which cells to ignore (for example, empty data, invalid data, outliers), and which cells so we can convert (converting string input from a file to numbers).

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without installing an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: