teaching machines

CS 145 Lecture 13 – Loop tricks

October 24, 2011 by . Filed under cs145, fall 2011, lectures.

Agenda

Code

ForAWhile.java

package lecture;

import java.util.Scanner;

public class ForAWhile {
  public static void main(String[] args) {
    
//    String command = "notdone";
//    for (Scanner in = new Scanner(System.in); !command.equals("done"); command = in.next()) {
//    }
    
    String command = "notdone";
    Scanner in = new Scanner(System.in);
    while (!command.equals("done")) {
      command = in.next();
    }
    
  }
}

MeanCellPhoneBill.java

package lecture;

import java.util.Scanner;

public class MeanCellPhoneBill {
  public static void main(String[] args) {
    
    double runningTotal = 0.0;
    int nSurveyed = 0;
    Scanner in = new Scanner(System.in);
    double bill = 0.0;
   
    // Ask first time
    System.out.print("> ");
    bill = in.nextDouble();

    // Tack on all bills until a negative read.
    while (bill >= 0.0) {
      ++nSurveyed;
      runningTotal += bill;
      System.out.print("> ");
      bill = in.nextDouble();
    }
    
    System.out.println(runningTotal / nSurveyed);
  }
}

LoopAndAHalf.java

package lecture;

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

    for (int i = 0; i < 3; ++i) {
      System.out.print("XO");
    }
    System.out.println("X");
    
  }
}

Chess.java

package lecture;

public class Chess {
  public static void main(String[] args) {
//    for (int i = 1; i < 9; ++i) {
//      System.out.printf("%3d", 1 * i);
//    }
//    System.out.println();
//    
//    for (int i = 1; i < 9; ++i) {
//      System.out.printf("%3d", 2 * i);
//    }
//    System.out.println();
//    
//    for (int i = 1; i < 9; ++i) {
//      System.out.printf("%3d", 3 * i);
//    }
//    System.out.println();
    
    
    
    for (int z = 1; z < 9; ++z) {
      for (int i = 1; i < 9; ++i) {
        System.out.printf("%3d", z * i);
      }
      System.out.println();
    }

  }
}

TODO

  1. Read chapter 5.