Lab 5 (Feb 11-12)

User-Defined Classes.

In this lab you will be on your own.

Use the lab time to design and test classes for assignment 5.

To avoid problems with the DOS window going away as soon as the program ends please use the following framework, illustrated in one of the examples from the Carl Lewis vs. Ben Johnson race lab.

If you run the code below:

public class Olympics {
  public static void main(String[] args) {
    Runner a = new Runner(" Carl Lewis");
    Runner b = new Runner("Ben Johnson"); 
    for (int i = 1; i <= 8; i++) {
      System.out.println("Seconds elapsed: " + i); 
      a.race(); 
      b.race(); 
      } 
    }
}

class Runner {
  private String name;
  private int yards;
  Runner(String givenName) { 
    name = givenName; 
    yards = 0; 
  } 
        
  void race() { 
    int leap; 
    leap = (int)(Math.random() * 6 + 1); 
    yards += leap; 
    System.out.println("  " + name + ": advances " + 
                       leap + " yards, " + "reaches " + 
                       yards + " yards."); 
  } 
}
the DOS window in which the program output is going will close as soon as the program finishes writing.

To make the program stop when you need it define a method pause()

public static void pause() {
  try {
    System.out.println("Press Enter to continue..."); 
    (new BufferedReader
      (new InputStreamReader
        (System.in))).readLine(); 
  } catch (IOException e) { } 
}
and invoke it when you need it. The italics identify your degrees of freedom.

Also make sure you

import java.io.*;
in your program.

It's really up to you where you want to define pause, but use it accordingly.

For example:

import java.io.*; 

public class Olympics {
  public static void main(String[] args) {
    Runner a = new Runner(" Carl Lewis");
    Runner b = new Runner("Ben Johnson"); 
    for (int i = 1; i <= 8; i++) {
      System.out.println("Seconds elapsed: " + i); 
      a.race(); 
      b.race(); 
      b.pause();  
    } 
    Runner.pause(); 
  }
}

class Runner {
  private String name;
  private int yards;
  Runner(String givenName) { 
    name = givenName; 
    yards = 0; 
  } 
  public static void pause() {
    try {
      System.out.println("Press Enter to continue..."); 
      (new BufferedReader
        (new InputStreamReader
          (System.in))).readLine(); 
    } catch (IOException e) { } 
  }  
  void race() { 
    int leap; 
    leap = (int)(Math.random() * 6 + 1); 
    yards += leap; 
    System.out.println("  " + name + ": advances " + 
                       leap + " yards, " + "reaches " + 
                       yards + " yards."); 
  }
}
In the example above pause and so it can be accessed both