teaching machines

CS 1: Lecture 20 – Loops, Part 2

October 25, 2017 by . Filed under cs1, cs145, cs148, fall 2017, lectures.

Dear students,

Three big ideas will consume the rest of our semester: loops, arrays, and objects. Nothing we’ve discussed so far will go away. We will be spending our days seeing applications of these ideas. Like today. Our entire time will be spent writing some applications that use loops.

Here’s your TODO list to complete before we meet again:

See you next class!

Sincerely,

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

There’s a bar downtown
The Loophole, where one loop stops
Here, have another

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

WordCounter.java

package lecture1025;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javax.swing.JFileChooser;

public class WordCounter {
  public static void main(String[] args) throws FileNotFoundException {
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File file = chooser.getSelectedFile();
    
//    File file = new File("/Users/johnch/Desktop/foo.txt");
    Scanner in = new Scanner(file);
    
    int nWords = 0;
    while (in.hasNext()) {
      in.next();
      nWords++;
    }
    
    System.out.println(nWords);
    
    in.close();
  }
}

Blugold.java

package lecture1025;

public class Blugold {
  public static void main(String[] args) {
    for (int i = 1; i <= 100; i++) {
//      if (i % 15 == 0) {
//      if (i % 3 == 0 && i % 5 == 0) {
//        System.out.println("blugold");
//      } else if (i % 3 == 0) {
//        System.out.println("blu");
//      } else if (i % 5 == 0) {
//        System.out.println("gold");
//      } else {
//        System.out.println(i);
//      }
      
      if (i % 3 == 0) {
        System.out.print("blu");
      }
      
      if (i % 5 == 0) {
        System.out.print("gold");
      }
      
      if (i % 3 != 0 && i % 5 != 0) {
        System.out.print(i);
      }
      
      System.out.println();
    }
  }
}

Circler.java

package lecture1025;

import java.awt.AWTException;
import java.awt.Robot;

public class Circler {
  public static void main(String[] args) throws AWTException {
    Robot bot = new Robot();
    int n = 3000;
    double radius = 100;
    double theta = 2 * Math.PI / n;
    for (int i = 0; i < n; i++) {
      int x = (int) (radius * Math.cos(i * theta));
      int y = (int) (radius * Math.sin(i * theta));
      bot.mouseMove(x + 1000, y + 500);
      bot.delay(100);
    }
  }
}