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:
the DOS window in which the program output is going will close as soon as the program finishes writing.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."); } }
To make the program stop when you need it define a method pause()
and invoke it when you need it. The italics identify your degrees of freedom.public static void pause() { try { System.out.println("Press Enter to continue..."); (new BufferedReader (new InputStreamReader (System.in))).readLine(); } catch (IOException e) { } }
Also make sure you
in your program.import java.io.*;
It's really up to you where you want to define
pause
, but use it accordingly.
For example:
In the example aboveimport 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."); } }
pause
Runner