Computer Science 252
Problem Solving with Java

Spring 2015, The College of Saint Rose

Lab 1: Java Review
Due: 11:59 PM, Thursday, February 5, 2015

This set of problems is designed to refresh and sharpen your prerequisite Java programming skills. There are several programs to write, but all are things you should be comfortable doing having completed the prerequisites successfully. As these will overlap with assignments and lab exercises on our new material, you will have the first three weeks of the semester to complete these.

You are to work individually on these programs.

Getting Set Up

To get your BlueJ environment set up for this week's lab assignment, start BlueJ and choose "New Project" from the "Project" menu. Navigate to your folder for this course and choose the name "Lab1" (no spaces) for the project.

Create a document where you will record your answers to the lab questions. If you use plain text, call it "lab1.txt". If it's a Word document, you can call it whatever you'd like, but when you submit, be sure you convert it to a PDF document "lab1.pdf" before you submit it.

Practice Programs

Practice Program: Write a program LongestWord.java that reads in a series of words from the keyboard until an empty string is encountered, at which point it reports the longest word(s) that were presented on the input. This practice program is worth 10 points.

It is essential to develop and test a program such as this incrementally. Below is a list of steps you can follow. You can (and should) stop and test your program after each step.

  1. Read in one word.
  2. Read in words inside a loop (forever).
  3. Read in words until someone enters the empty string ("").
  4. Add a variable that keeps track of the number of words read in. Initialize it before your main loop, increment it in an appropriate place inside your main loop, and print it out after the loop.
  5. Add a variable to keep track of the longest word. Update it in your main loop any time someone enters a word longer than the longest seen previously. Print it out at the end. Don't worry yet about handling ties.
  6. Now worry about that case. When you detect a tie for the longest word, you should append the new word to the string containing the longest word(s). Note that we will now need to have a separate variable to remember the length of the longest word, since the string containing the longest word(s) may now contain multiple words.
  7. Add a check at the end to make sure you only print the longest word(s) if at least one word was entered before "" was entered. If not, print a separate message to that effect.

Practice Program: Write a Java program named Seq.java that clones some of the functionality of the Unix seq command, which prints sequences of numbers starting at a lower bound, continuing to an upper bound by some increment. This practice program counts for 20 points.

If you haven't used command-line parameters, don't worry, the idea is pretty straightforward. If your main method is specified correctly:

   public static void main(String args[])

then args contains the values passed on the command line to your program. The idea comes from running commands in a terminal window, but you can do it in BlueJ also. args is an array, a topic we will study in more detail later in the semester.

In BlueJ, we specify the command line parameters as part of the process of launching a Java application. Any Java application is launched with a right-click in the Project Window on the class that contains the main method we wish to run, and choose "void main(String[] args)" to launch the main method.

The command-line parameters are then specified in the window that pops up as a list of string literals inside curly braces, separated by commas (yes, really). So to run with command-line parameters "10 20", one would specify:

Back in the program, args.length is the number of command-line parameters, and the actual strings are in args[0], args[1], args[2], etc..

The program should take 1, 2, or 3 numeric command-line parameters. Note that the command-line parameters will come to you as strings, and will need to be converted to integers before they can be used. One possibility is to use the Integer.parseInt method. For example, to put the int value into a variable x from a String in args[0], one could use:

int x = 0;  // a default to satisfy Java that x will have a value
try {
   x = Integer.parseInt(args[0]);
}
catch (NumberFormatException e) {
  System.err.println("Could not convert " + args[0] + " to int");
  System.exit(1);
}

If there is 1 parameter, it indicates the upper bound of the list of numbers to be printed, starting at 1, counting by 1. So command line parameters specified as { "5" } would result in output

1
2
3
4
5

If there are 2 parameters, they specify the starting and ending values for the counting by 1. So command line parameters { "3", "7" } would result in output

3
4
5
6
7

When 3 parameters are specified, the first is the starting number, the second the amount to increment, and the last the upper limit of the counting. So command line parameters { "-3", "4", "10" } would result in output

-3
1
5
9

If your program is presented with invalid command line parameters (e.g., there aren't the right number of parameters, the parameters cannot be converted to integers, or they otherwise make no sense), your program should print an appropriate error message and exit. Your program should result in correct output for all cases of parameters that make sense, and print errors in cases where they don't.

Once you have valid parameters and have handled all of the input, you just need a couple of loops to do the printouts.

This program will be graded entirely on the number of example input tests that it handles correctly. These will include incorrect numbers of parameters, non-integer parameters, numeric parameters that don't make sense (e.g., counting from 1 to 10 by -1), and of course, a variety of valid input parameters.

Programming Assignment: The Lottery "Numbers" Game

The lottery game we will be simulating is the New York Lottery's "Numbers Game". In this game, a bettor wagers on which random number between 000 and 999 will be selected that day. The payoff is 500:1, i.e., for a $1 bet, a match will result in a $500 payout. A $2 bet will result in a $1,000 payout, etc.. This sounds great to anyone who never passed 6th grade math. In reality, if you play this game long enough, you will lose half of your money.

Simple Simulation

Develop a simple Java application, which you should call LotterySimulation.java, that simulates a specified number of lottery drawings, given the number to bet on and the amount of a bet. Each of these three are read in from the keyboard (use a Scanner).

For example, if the number of drawings to simulate is 10, and the number to bet on is 284, betting $2 per drawing, a series of 10 random numbers in the 0-999 range should be drawn. For each number drawn, we keep track of the fact that another $2 has been bet. If the number came up as 284, we also record that the winnings for that drawing are $1,000, and that amount is added to the accumulated winnings. In the end, report the total amount that was bet and the total winnings, followed by a statement that reports either the net amount won, the net amount lost, or that the bettor broke even.

Question 1: For the above example input, what are all of the possible values for total amount bet, total winnings, and net winnings/losses? Hint: consider what would happen if the player wins 0 times, 1 time, 2 times, etc.. (3 points)

Question 2: Run your program for the above example input and report your results. (2 points)

Adding File I/O

Once that it working, your next task is to get some of your input (the number to bet on and the amount of each bet) from a file, and to write all of the program's output (other than Terminal prompts) to a file.

Your program should prompt (at the Terminal) for the name of the input file that contains the number to bet and the amount of each bet, for the name of the file that should contain the simulation output, and for the number of drawings to simulate.

You will need to create your plain text input file in the same folder as your BlueJ project. In Windows, you can use Notepad. On a Mac, TextEdit is a good choice. The file should consist of only the 2 numbers: the number to bet on and the amount of the best, on a single line, separated by a space.

Processing Multiple Bets Per Drawing

Finally, for just the last few points, extend your program so it reads 3 numbers to bet on and amounts of those bets. Place these on 3 lines, a number and a bet amount on each line. For each drawing, all 3 bets are placed and processed.

Note: given the Java constructs we have been using so far, the best way to accomplish this is to introduce extra variables to store the additional numbers and bet amounts, and to add code inside your main loop that checks for a possible win for each of the three numbers rather than just the one.

The program's correctness is worth 35 points, with style an additional 10.

Submitting

Before 11:59 PM, Thursday, February 5, 2015, submit your lab for grading. There are three things you need to do to complete the submission: (i) Copy your file with the answers to the lab questions into your project directory. Be sure to use the correct file name. If you prepared your answers in Word, export to a PDF file and submit that. (ii) Upload a copy of your lab (a .7z or .zip file containing your project directory) using Submission Box under assignment "Lab1". (iii) Demonstrate the execution of your programs for your instructor. (2 business day grace period for demos).

Grading

This assignment is worth 80 points, which are distributed as follows:

> FeatureValueScore
LongestWord correctness 10
Seq correctness 20
LotterySimulation Input parameters (file names and number of drawings) 3
LotterySimulation Reads one number and bet amount from file 5
LotterySimulation Reads three numbers and bet amounts from file 3
LotterySimulation Main loop (correct number of drawings) 3
LotterySimulation Random drawings 3
LotterySimulation Correctly reports bet amount and number for each drawing 4
LotterySimulation Correctly detects and reports win/loss on a drawing 5
LotterySimulation Reports simulation results at the end 5
LotterySimulation Simulation output (but not prompts) to file instead of terminal 4
LotterySimulation comments 5
LotterySimulation naming conventions 3
LotterySimulation formatting 2
Lab Questions 5
Total 80