teaching machines

CS1: Lecture 11 – More Methods

September 27, 2019 by . Filed under cs1, fall 2019, lectures.

Dear students,

We’ll spend today continuing our discussion of methods—because we need practice. Java is a language, one invented by someone else, and we need to both speak it and hear it regularly in order to acquire it. Let’s start with an exercise in hearing Java, but with some parts inaudible.

Fill in the Blanks

Sometimes Java is criticized for being verbose. But one of the great advantages of verbosity is the reinforcement that it brings to an expression. We may read a passage and not know every word, but there are often many clues lying in the context to help us determine their meaning. Java has these same advantages. We can look at a method and figure out a lot of things from how a values are operated upon.

To gain some sensitivity for reading this context, let’s complete several fill-in-the-blank exercises. Your task is to jot what goes in each blank of the following methods. One of the blanks is the method name. Pick something meaningful. The other blanks are not ambiguous. You should be able to deduce exactly what goes there.

Blackbox

Let’s play a little game called Blackbox. After we figure out what these blackboxes do, we’ll implement them in Java.

TODO

Here’s your TODO list for next time:

See you next class!

Sincerely,

P.S. It’s time for a haiku!

Why is it method
Surely there’s a better name
But meth was taken

P.P.S. Here’s the code we wrote together in class…

Frankenstring.java

package lecture0927.cs145;

public class Frankenstring {
  public static void main(String[] args) {
    System.out.println(frankenstring("eau claire", "nice"));
  }

  public static String frankenstring(String a, String b) {
    int i = a.length() / 2;
    int j = b.length() / 2;
    String monster = a.substring(0, i) + b.substring(j);
    return monster;
  }
}

Blackboxes.java

package lecture0927.cs148;

public class Blackboxes {
  public static void main(String[] args) {
    System.out.println(repeat('x', 'o', -3));
  }

  public static String repeat(char x, char o, int n) {
//    (("" + x + "" + o) * n) + x
    return ("" + x + o).repeat(Math.max(n, 0)) + x;
//    subject.repeat(n)
  }
}