Software Development, Design Choices, Class Design, Recursion and Iteration, Testing, and Command-line Arguments |
2011-2012 | |
A Racquetball or Volleyball Simulation | ||
Although previous programs have provided relatively simple implementations of a racquetball/volleyball simulation using static fields and/or an object's field variables, a user must edit each program, recompile, and rerun to change between racquetball and volleyball.
Another approach utilizes a command-line parameters to allow the user to specify the game when the program is run — without having to edit and recompile. In this approach, the program utilizes String parameters in the main method to determine which game is desired.
To get started, recall that a program includes these static variables:
public static String game; // "racquetball" or "volleyball" public static int numberOfGames = 1000; public static boolean winByTwo; // winner must be ahead by at least 2 points
The following code shows a very simple mechanism at the start of main to accomplish this work.
public static void main (String [] args) { game = ""; // initially, game is unspecified // check any command-line argument if (args.length >= 1) { game = args[0]; } // determine if server must win by 2 (e.g., in volleyball) winByTwo = game.equals("volleyball"); // the remainder of the program proceeds as before ... }
Program Game4Recur.java gives a recursive implementation with a command-line argument and with tracing a tracing variable (initially set to false.
Run Game4Recur.java with these command lines:
java Game4Recur racquetball java Game4Recur volleyball java Game4Recur java Game4Recur swimming java Game4Recur racquetball volleyball java Game4Recur volleyball racquetball
Describe what happens in each case.
Review the code of Game4Recur.java, and explain how the code at the beginning of main works.
Revise Game4Recur.java, so that the user can supply both the game and the number of games to be simulated on the command line.
Expand your program from the previous step to perform error checking. For example, one error might be printed if the user provides the wrong number of parameters. Another error might be printed if the name of the game is incorrect. Yet another error might be printed if the string with the number of games is not a positive integer.