CS 199 EMP

Hosted by Jackie Chan and Akhila Ashokan

Topics: Assertions, Do-While Statements, Switch Statements, and More Multidimensional/String Problems

Today's Learning Objectives

Review and practice:

  • Assertions
  • Do-While Statements
  • Switch Statements
  • More Multidimensional/String Problems

Write code on the homepage or any playground on the site!
https://cs125.cs.illinois.edu/

Slides are on the course site!
https://cs199emp.netlify.app/

Assertions to Confirm Functionality

Assertions are there for you. They exist so that you know that a code snippet is operating in a certain way. Assertions will be used as test cases for your code.

Assertions take conditional expressions and assert that they should be true, otherwise it'll stop the code.

int sum(int[] arr) {
  int sum = 0
  for (int i : arr) {
    sum += i;
  }
  return sum;
}

// The sum of this sequence should be 15, and the assertion says
// 15 == 15, if not, then we know that sum goofed up.
assert 15 == sum(new int[]{1, 2, 3, 4, 5});
assert 12 == sum(new int[]{0, -1, 5, 8});

Practice with Assertions through Test-Driven Development (5 minutes)

Write some test cases, using assert, that a function that counts the number of times a word appears in a sentence (no punctuation, lowercase).

int count = count("geoff goes to the store and buys cashews", "cashews");
System.out.println(count); // prints 1

Good test cases are diverse and cover edge cases.

"An edge case is a problem or situation that occurs only at an extreme" [Wikipedia] For example, consider what count() should do with: empty strings, null, "" as the word to be counted.

With These Test Cases, Implement! (10 minutes)

int count(String sentence, String word) {
    // Your code.
}

// Your test cases.

You may want to comment out certain test cases initially, but when count is fully implemented, then all the test cases should pass.

Do-While Statements, Why?

Do-While statements are important when you want the code within a while statement to run at least once.

In reality you don't often need it (some may say it's bad practice), but in some situations a do-while statement may look more elegant/reflect the reality of the situation better.

Practice with Do-While Statements: Web Page Request

Given this code to request a webpage, have a do-while loop that requests until successful or when it has tried at least ten times. Print something if it fails ten times.

// Don't worry about what this does or means.
import java.util.Random;

boolean requestWebPage() {
  Random rand = new Random();
  
  if (rand.nextInt() % 2 == 0) {
    System.out.println("Webpage successfully retrieved!");
    return true;
  } else {
    System.out.println("Webpage unsuccessfully retrieved!");
    return false;
  }
}

Switch Statements, Why?

Switch statements may be helpful for situations where you have multiple different things you want to do that is dependent on some expression. The expressions can be String, int, and char.

Some keywords to know with switch statements are: case, break, default, ->, and yield.

Use -> as a substitute for break statements.
Use yield if you want the switch statement to return/assign a value.
Use default as an equivalent to an else in if statements.

Recall the switch statement syntax here.

switch (day) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
    System.out.println("Go to class and study.");
    break;
  case "Friday":
  case "Saturday":
    System.out.println("Party!");
    break;
  case "Sunday":
    System.out.println("Recover and cram.");
    break;
}

Practice with Switch Statements (5 minutes)

Convert this if statement chain into a more elegant switch statement.

String situation = "Morning";
boolean makeCoffee;

if (situation.equals("Morning")) {
  makeCoffee = true;
} else if (situation.equals("Afternoon") || situation.equals("Evening")) {
  makeCoffee = false;
} else if (situation.equals("Cramming")) {
  makeCoffee = true;
} else {
  makeCoffee = false;
}

Bonus Multidimensional/String Problem (15 minutes)

Write a function that goes through String[][] tweets where the first dimension is particular tweet and String[i][] = new String[]{"jackiec3", "Hello Twitter!"}, i.e. the second dimension contains two strings, the username and tweet.

Simplify the tweets so that there's no punctuation and they're lowercased.

Loop through each of these and replace the tweet if it contains a bannedWord, then replace the tweet with [removed].

Return the tweets.

Twitter Starter Code

void printTweets(String[][] tweets) {
  for (String[] tweet : tweets) {
    System.out.println(tweet[0] + " tweeted: " + tweet[1]);
  }
  return;
}

String[][] banTweets(String[][] tweets, String bannedWord) {
  // Your code here.
}

String[][] tweets = {
    {"jackie", "i'm having a wonderful day today"},
    {"akhila", "not a good day for programming for me"},
    {"geoff", "my students are awesome"}
};

filteredTweets = banTweets(tweets, "day");
printTweets(filterTweets)

That's it for today!

Thanks for sticking around. Remember that next week is the midterm!

Have a good weekend, relax, stay safe, stay healthy.

Fill out the feedback form if you have the chance!

Solution Section

Practice with Assertions through TDD Solution

// basic test case
assert 5 == count("dog dog dog dog dog", "dog");

// testing empty word
assert 0 == count("have a good day", "");

// testing empty sentence
assert 0 == count("", "dog");

// testing null word
assert 0 == count("giving null", null);

// testing null sentence
assert 0 == count(null, "oops");

With Test Cases, Implement! Solution

int count(String sentence, String word) {

  if (sentence == null || word == null) {
    return 0;
  }

  String[] words = sentence.split(" ");
  int count = 0;

  for (String sentenceWord : words) {
    if (sentenceWord.equals(word)) {
      count++;
    }
  }

  return count;
}

assert 5 == count("dog dog dog dog dog", "dog");
assert 0 == count("have a good day", "");
assert 0 == count("", "dog");
assert 0 == count("giving null", null);
assert 0 == count(null, "oops");

Practice with Do-While Statements: Web Page Request Solution

int attempts = 0;
boolean successful = false;

do {

  attempts++;

  successful = requestWebPage();

} while (attempts < 10 && !successful);

if (!successful) {
  System.out.println("Wow you're very unlucky!");
}

Practice with Switch Statements Solution

String situation = "Morning";
boolean makeCoffee = switch (situation) {
    case "Morning" -> true;
    case "Cramming" -> true;
    case "Afternoon" -> false;
    case "Evening" -> false;
    default -> false;
};

System.out.println(makeCoffee);

Bonus Multidimensional/String Problem Solution

String[][] banTweets(String[][] tweets, String bannedWord) {

  for (int i = 0; i < tweets.length; i++) {
    String[] words = tweets[i][1].split(" ");
    
    boolean ban = false;
    
    for (String word : words) {
      if (word.equals(bannedWord)) {
        ban = true;
      }
    }
    
    if (ban) {
      tweets[i][1] = "[removed]";
    }
  }
  
  return tweets;
}