teaching machines

CS 145 Lecture 21 – Loops Cont’d

October 28, 2016 by . Filed under cs145, fall 2016, lectures.

Dear students,

Let’s start with a little Program This:

Write a method indexOf that accepts a String and a char as parameters. Without using the builtin String.indexOf method, it returns the index at which the given character resides in the String. If no such character can be found, return -1.

Then, let’s seem some more example of loops:

Before we meet again, please do the following:

See you next class!

Sincerely,

P.S. It’s Haiku Friday!

They don’t go crazy
So why’d Robot cross the road?
Chicken programmed it

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

BradBrad.java

package lecture1028;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class BradBrad {
  public static void main(String[] args) throws IOException {
    BufferedImage image = new BufferedImage(512, 256, BufferedImage.TYPE_INT_RGB);
    Color color = new Color(0, 255, 255);
    image.setRGB(100, 100, color.getRGB());
    
    ImageIO.write(image, "png", new File("/Users/johnch/Desktop/image.png"));
  }
}

Stringing.java

package lecture1028;

public class Stringing {
  public static void main(String[] args) {
    String s = "Abraham";
    
    System.out.println(indexOf(s, 'm'));
    System.out.println(indexOf(s, 'a'));
    System.out.println(lastIndexOf(s, 'a'));

  }
  
  public static int indexOf(String s, char c) {
    for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) == c) {
        return i;
      }
    }
    return -1;
  }
  
  public static int lastIndexOf(String s, char c) {
    for (int i = s.length() - 1; i >= 0; --i) {
      if (s.charAt(i) == c) {
        return i;
      }
    }
    return -1;
  }
}

Chess.java

package lecture1028;

public class Chess {
  public static void main(String[] args) {

    // For each row
    for (int r = 1; r <= 8; r++) {

      // For each column
      for (int c = 1; c <= 8; c++) {
        System.out.printf("%3d", r * c);
      }
      System.out.println();

    }
  }
}