Program 2

Programming Basics
(Expressions and Statements)

Advanced Programming/Practicum
15-200


Introduction This programming assignment is designed to ensure that you know how to write simple programs that combine expressions (arithmetic, relational, logical, textual, and state-change operators, as well as input/output methods) and standard statements (declaration, expression, block, if, loop, break). It also introduces iterative-enhancement, a divide-and-conquer approach to writing, testing, and debugging programs; we will cover this approach in more detail in a lecture soon. You will write just two programs in this assignment (during the first few weeks, I want to ensure that you have adequate time to read the lectures and work their problems; as the lectures get shorter, the programming assignments get longer).

Programming assignments typically are linked to executable solutions. That is, you can download and run these Executables to help you understand the specification of the problem and observe the programmer/user interaction you are to implement. But, you cannot examine the their underlying Java code. If you need a data file to run the program, it will appear here too; use it for the executable solution and the program you write. Copy the input/output form of the executable programs; use exactly the same prompts and messages.

On a PC, you can run the application just by double-clicking the file named double click me.bat. You can run the Application.jar file in Eclipse (on any platform) by making project of the executable folder named darts or rocket (just one of these). Then, disclose the default package, and right click Application.class, and then select Run As and Java Application.

Write each program in its own project folder: you should name them accordingly (e.g., darts and rocket); then put both folders in another folder whose name combines your names (when programming in pairs) and the program number (e.g., pattis-stehlik-2). Then zip this folder and dropoff that single zip file. Each pair should submit one project: either partner can submit it.

IMPORTANT: Create new, empty projects for each of these programs. You must add the line

  import edu.cmu.cs.pattis.cs151xx.Prompt;
in your class (I use Application as the name of a generic program class), between the main comment (see below) and declaration of the class. Please cut/past/fill in the following comment at the top of your code.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// Name/e-mail	  : e.g., Richard Pattis/pattis@cs.cmu.edu and
//                        Mark Stehlik/mjs@cs.cmu.edu;
//                        You must list both in paired projects
// Course/Section : e.g., 15-200/Section A
// Program #/Name : e.g., Program #1/Simple Input/Output
//
// Description:
//
//    Fill in this section with a description of your program. A good rule of
// thumb is that a description should be about 1/10th to 1/5th the size (in
// lines) of the program (in lines) that it describes.
//
// Known Bugs (if any): (if you know about/explain a bug here, you will lose
//                       less credit for it than if you don't acknowledge it).
//
// Program History:
//   List dates for any major events in the program's life-cycle: e.g.,
//    program started, removal of a major bug, program finished; get into the
//    habit of documenting (with an audit trail) major changes to every file
//    that you edit. The first entry might be...
//   9/7/05: R. Pattis/M. Stehlik  - Started program, working as a pair
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

Calculating pi with Darts Write a program that performs the following tasks.
  • Prompt the user for the number of darts to throw (accept only numbers greater than 0, reprompting the user whenever a non-positive value is entered)
  • Simulate throwing that many darts at a 2x2 square whose center is the origin by using a random number generator, constrained by the square's boundary, to generate x and y coordinates for each dart.
  • Approximate the value of π (pi) by computing the ratio of those darts that land inside a circle inscribed in the square divided by the number of darts that landed inside the square (the total number of darts thrown, since all darts are constrained to land in the square).
That calculation approximates the ratio of the circle's area to the square's:

To simulate throwing darts, develop an expression that returns a result in the range -1.0 to +1.0 that calls the Math.random method, which returns a result between 0.0 and 1.0, and use this expression when generating the x and y coordinates. Doing so ensures that both coordinates are within the square.

Use a boolean expression to determine whether or not the coordinates of the dart are inside or outside the circle that is inscribed in the square (remember some geometry).

Design, code, test, and debug this program using iterative-enhancement, as 6 mini-projects. Test each project to ensure that it is correct before proceeding to the next enhancement. This is the same methodology that we will use for larger programs; so, it is a good idea to practice this technique here, where the program is small, even if you can write the entire program all at once. Later, we will discuss this technique in greater depth. Before starting to write your program, run mine executable a few times to familiarize youself with its input and output.

  1. Write a kernel program that prompts the user for the number of darts to throw, and then loops that many times, printing the literal "Dart Thrown" for each loop iteration. Here, assume the user always enters a positive number. Ensure the number of times Dart Thrown is printed is the same as the requested number of darts (it is easy to be off by 1). Enter a few different small values to test it.

  2. Enhance the program so that it throws a dart during each iteration, and prints the random x- and y-coordinates of each dart as it is thrown. Ensure that these values change, and are all between -1. and +1.

  3. Enhance the program so that after it prints the x- and y-coordinates of each dart, it prints either "Inside Circle" or "Outside Circle" for that dart's coordinates. Using a calculator, hand check that the inside/outside calculation is computing its result correctly for a few darts printing each message.

  4. Enhance the program to keep track of (count up) the number of darts that land inside the circle, and display this value during each iteration of the loop. Ensure that for each dart that lands inside the circle, this count increments by one. IMPORTANT REQUIREMENT: All counters in Java should be of type int; use explicit conversion (casting) if you need to treat these values like doubles, in some computation.

  5. Enhance the program to approximate π (pi) by computing the ratio of darts that land in the circle to the total number of darts thrown, multiplying this value by 4 (the area of the circle) according to the formula above. Display this result before terminating.

  6. Enhance the program to allow the user to enter only positive values in the original prompt for the number of darts to throw; reprompting whenever the enters a non-positive value. Use a separate loop for this validation; do not use any fancy version of Prompt.forInt: just use the simplest one with a single String operand). Test your code by trying to enter 0 and/or negative numbers.
Finally, remove all intermediate output statements: only the final answer should appear in the final output (it should produce exactly the same output as my executable) Hand in ONLY THE FINAL ENHANCEMENT of the program: the one meeting the complete specifications, with intermediate output statements removed. Test it by throwing 10; 100; 1,000; 10,000; 100,000, 1 million, and 10 million darts. Also, try the same number of darts more than once and observe that the computed value changes, because the darts are thrown randomly each time. Typically, the more darts thrown, the better the answer approximates the true value of π (pi).

Simulating the Flight of a Rocket Write a program that performs the following tasks.
  • Prompt the user to enter the following information describing the rocket:
    • Thrust (in pounds)
    • Thrust Duration (in seconds)
    • Mass (in pounds)
    Assume that the user always enters reasonable values; do not write input validation code for this part of the assignment.
  • Prompt the user, asking whether to print a detailed trace of the flight
  • Simulate the rocket flying vertically (straight up), using these values and a simulation time increment of .01 seconds. If the user requested tracing, print the time, thrust, acceleration, velocity at the end of the interval and height at the end of the interval. Continue the simulation until the rocket reaches its apex (its velocity, which is initially zero, then positive as the rocket ascends, begins to go negative).
  • Print the following information, accumulated over the rocket's entire flight
    • The total impulse (entered thrust times thrust duration)
    • The total flight time (burn + coast time)
    • The burn time (thrust duration)
    • The coast time (time from the end of the thrust to the apex)
    • The maximum velocity it achieved during the entire simulation
    • The maximum height it achieved during the entire simulation
The basic formula for simulating rocket flight is
          th - cd v2
    a = -------------  - g
             m
We recompute this formula for every time interval during the simulation. In it a, the acceleration for that time interval, is computed from
  • th is the thrust (from time zero up to the thrust time, use the entered thrust, after that the thrust is zero while the rocket is coasting)
  • cd is the coefficient of drag (use .0001 in the program)
  • v is current velocity (at the start of the interval)
  • m is the mass of the rocket
  • g is the gravitational acceleration on the surface of the earth: 32.17 feet/sec/sec
The rocket starts at time 0. with its height and velocity both 0. For each time interval of .01 seconds (let's call it dT), the program (a) increments the total time by dT, (b) calculates the acceleration of the rocket (from the formula above) for that time interval; remember to use the correct thrust, depending on the time, and (c) calculates the new velocity and height (at the end of the time interval) as follows:
  • The new (end of the time interval) velocity, which is the old (start of the time interval) velocity + a * dT; the average velocity over the interval is the average of the old and new velocities.
  • The new (end of the time interval) height, which is the old (start of the time interval) height + the average velocity * dT.
  • The maximim velocity and height, which may be updated depending on their values at the start of the time interval and at the end of the time interval.

Design, code, test, and debug this program using iterative-enhancement, as 6 mini-projects. Test each project to ensure that it is correct before proceeding to the next enhancement. This is the same methodology that we will use for larger programs; so, it is a good idea to practice this technique here, where the program is small, even if you can write the entire program all at once. Later, we will discuss this technique in greater depth. Before starting to write your program, run mine executable a few times to familiarize youself with its input and output.

  1. Write a kernel program that prompts the user for all the rocket information specified above, and then loops, incrementing the time (until it exceeds the time that the engine stops burning), displaying the time and thrust for each time interval. Ensure the time and thrust are displayed correctly, and the loop terminates at the correct time. Don't worry about doing anything with the mass.

  2. Enhance the program so that it computes the acceleration and then the velocity (which starts at 0.) correctly; change the loop to terminate when the velocity becomes negative (the rocket has reached its apex and is falling back to earth). During each iteration of the loop, compute the acceleration using the formula shown above, and update the velocity using the description shown above. In addition to displaying the time and thrust (which should reduce to 0. at the correct time), display the acceleration for the interval, and the velocity at the end of the interval.

  3. Enhance the program so that it computes the height (which starts at 0.) correctly. During each iteration of the loop, update the height using the formula shown above. In addition to displaying everything else, display the height at the end of each time interval.

  4. Enhance the program to keep track of the maximum velocity and height. In addition to displaying everything else, display these values at the end of each time interval. Finally, display these values after the loop terminates. Test this program completely by first using a small thrust (50 lbs), a short duration (.1 secs), with a small mass (1 lb.) and then compare all its output to the output of my executable.

  5. Enhance the program to display all the required information after the loop terminates (display this information in the correct form)

  6. Enhance the program to prompt the user about tracing, and then display the intermediate results only if the user enters true.
Use final appropriately when declaring variables representing the information needed for this program.

Hand in only the final enhancement of the program: the one meeting these complete specifications (note that the program you submit SHOULD NOT print any intermediate results unless the user explicitly requests tracing). Test your debugged/completed program for a thrust of 100 lbs, a time of 10 secs, and a mass of 1 lb and compare it to the results of my excutable; for full credit your results should match exactly (certainly to most of the many digits printed by a double).