CSCE 145 -- Spring 2008

Sections 4, 5, 6

Introduction to Algorithmic Design

Lab Assignments

Lab Assignment 24

(Friday, 25 April 2008)

There will be no lab on this last Friday. We will use the time for review prior to the final exam, which will be administered at 2pm on Wednesday, 30 April 2008.

Lab Assignment 23

(Wednesday, 23 April 2008)

You are to adapt two programs from the Java Foundations chapter to create a slightly more interesting program.

Specifically, you should start with the temperature conversion program of page 249 and adapt it so that the input text is taken to be a temperature and two pushbuttons allow you to interpret the input as a Fahrenheit temperature and convert to Celsius or to interpret as Celsius and convert to Fahrenheit.

You don't have to change the main program a bit except to change the class name from Fahrenheit to something else (perhaps "LabOne").

In the LabOne class you will need to declare one text field, one output label, and two buttons. The text field is for input of the integer number that is the temperature to convert. One of the two buttons should be for Fahrenheit to Celsius and the other should be for Celsius to Fahrenheit to Celsius.

The output label is somewhat more complicated. Rather than use one label for the static text of the output message and one for the "result", I suggest that you start with a generic label that reads
xxx in C/F is yyy in F/C
and then as you push the buttons your code should create a new string for the output and assign that as the text for the label. This is done in my version of this program, for example, with

outputLabel.setText (inputText + " Fahr is " + Integer.toString (celsTemp) + " in Celsius")


NOW, SOME THINGS TO WATCH OUT FOR.

First, you must think about the actions to be performed and how your program is to respond to these actions.

One action will be to type in the input text in the text box.

Typing in the input text is NOT going to send the text to the program, however. That happens ONLY when you hit return, because it is the carriage return that triggers the ActionListener.

Another action is to push one of the two conversion buttons.

Now, let's think a minute. UNLESS you hit return after having typed in a number in the text box, the program will not have an input value for the input temperature.

But if you hit return after typing a number in the input text box, then you need to make sure that the input still lives after the ActionListener finishes. If the input text is a variable declared in the ActionListener, then that text will disappear when the ActionListener returns control back to the LabOne class.

What this means is that you will need to create an instance variable of the LabOne class to hold the input text. If you do this, then the ActionListener with set a value for that and that value will persist as long as LabOne exists, which is at least until you get a chance to push one or both of the buttons.

Note that the sample code from Java Foundations defines the string for the input text inside the ActionListener, and this will simply not work for this program.

Finally, your ActionListener will need to listen for actions from three different sources: the input text box carriage return and either of the two buttons. This will be done with an if-else just as the page 246 LeftRight code listened for two buttons.

NOTE: You may have to experiment slightly to get the popup sized properly. With the original 300x75 I found it too wide and the output label text was on the same line as one of the buttons. When I changed the size to 250x150 it looked ok.

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 22

(Friday, 18 April 2008)

You are to write a program to read in an array of numbers and to put them into bins so as to have a frequency count by bins.

Sample data can be found here. This is a file of "somenumber" of numbers, with the count "somenumber" being an integer value at the top of the file. In your getData() method, read that number in first, then allocate an array of that length, then read in "somenumber" numbers into the array, just as you did for the previous lab. As with the previous lab, for debugging purposes you probably want to change that first number to make it small so you can test your program. With something like a thousand numbers, you're not going to be able to test by hand. If you change that count to something like ten, you can check correctness by hand, and all you have to change is the first number in the data file. (Or else make a copy of the original data file and change the number in the copy file and use the copy for testing purposes.)

Note that all these numbers are between zero and 1.0. You may assume that this is true.

Your main method should have created an instance of a class DataIntoBins in which the getData() method lives. After you have read in the data, your main method should then invoke a binData(howMany) method that computes the number of the numbers in each of the howMany bins. For example, if there are to be 10 bins, your program should count the number of numbers

in bin 0 for numbers in the range 0.0 and strictly less than 0.1
in bin 1 for numbers in the range 0.1 and strictly less than 0.2
in bin 2 for numbers in the range 0.2 and strictly less than 0.3
and so forth

HINT: In this case, with the numbers between 0.0 and 1.0, you can multiply the data number by the number of bins and then cast that number to an int in order to get the correct bin to increment. That is, if you have 20 bins, and the data number is 0.149, it belongs in the bin for numbers from 0.10 up to but not including 0.15, and that is the third bin, which has subscript 2 if you are indexing from zero (0.0 to 0.5, 0.5 to 1.0, and then 1.0 to 1.5). Multiplying 0.149 by 20 gives you 02.98. Casting this to an int throws away the decimal part and leaves you with the 2, which is what you want for a subscript into your array of bins.

After your main method computes the bin counts, it should invoke a printBinCounts() method that prints back to the console the bin boundaries (0.0 to 0.1, 0.1 to 0.2, etc.) and the bin counts.

My program says that these are the data numbers and the bin counts if you cut the count of numbers back to 9 and use ten bins.

 0    0.58643
 1    0.85775
 2    0.06469
 3    0.16256
 4    0.04655
 5    0.24840
 6    0.55481
 7    0.42742
 8    0.04897

sub   lower upper count
  0    0.0   0.1   3
  1    0.1   0.2   1
  2    0.2   0.3   1
  3    0.3   0.4   0
  4    0.4   0.5   1
  5    0.5   0.6   2
  6    0.6   0.7   0
  7    0.7   0.8   0
  8    0.8   0.9   1
  9    0.9   1.0   0

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 21

(Wednesday, 16 April 2008)

You are to write a program to compute means and deviations given a list of input data values.

Sample data can be found here. Note that there are 20 values in this file. You don't want to debug something like this with 20 values. If you change the initial value of 20 to something small like 4, then you can do the arithmetic with a calculator to verify that you are getting the right answers. My program says the mean and deviation of the first four numbers are 41.32750 and 19.82862, respectively, and that the mean and deviation of all 20 are 42.62500 and 23.54860.

The mean of a list of numbers is what we usually refer to as the average. It is the sum of the numbers divided by the number of numbers. The standard deviation is defined thus: If XBAR is the mean of an array N numbers X[i], then the standard deviation is

sqrt(sum((X[i] - XBAR)*(X[i] - XBAR))/N).
That is, for each entry X[i], compute the sum of the squares of X[i] - XBAR, then divide by N, and take the square root.

You should read the data from a file set up as a Scanner in the main program.

You should have a getData() method that first reads the (integer) number of numbers from the top of the input file, then creates an array of double values of that length, then reads the numbers into the array. The number of numbers and the array should be instance variables of a MeanDev class.

You will probably want a printData() method just to make sure you got the numbers read in correctly.

Your main program should then invoke a computeMeanDev() method that will compute the mean and standard deviation. There is a mathematical formula for doing this in one step, but it's easier to do this with two loops. Use the first loop to sum the numbers, and then divide by N to get the mean. Then run a second loop to subtract the mean from each entry, square that difference, sum it up, and afterward divide by N and use Math.sqrt() to get the deviation itself.

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 20

(Friday, 11 April 2008)

You are to write a simple program to read in the coefficients of a polynomial and then to enumerate the values of that polynomial in a table.

Your main program should open a file for input as usual as a Scanner. Your main program should also create an instance of a class called MyPolynomial.

The getData(Scanner inDatafile) method should read first the integer that is the degree n of the polynomial and then the n+1 coefficients of the polynomial. The coefficients of the polynomial should be read into an array of double values.

PLEASE REMEMBER THAT A POLYNOMIAL OF DEGREE TWO HAS THREE COEFFICIENTS, A POLYNOMIAL OF DEGREE THREE HAS FOUR COEFFICIENTS, AND SO FORTH.

You should view the polynomial as being written

p(x) = a_0 + a_1 * x^1 + a_2 * x^2 + a_3 * x^3 + ... + a_n * x^n
so the coefficients should be input to the array with the constant term first and the coefficient of the highest order term last. This will allow you to run a loop from 0 through n and the loop subscript will coincide with the degree of the term being considered.

After your main program invokes the getData(Scanner inDatafile) method to read in the coefficients, your main program should then invoke a printPolynomial() method to print the polynomial's coefficients as a way of verifying that you have all the coefficients correct. Your output can go to the console.

Your main program should then invoke a printTable(double first, double last) method to print out the value of the polynomial at p(first) through p(last) in increments of 1.0. You can use the Math.pow(*) method (google "java 6 math" for the documentation) to compute the powers of x that you will need for this.

Your table should be formatted using printf so that the columns line up.

Upload to the dropbox as usual.

Lab Assignment 19

(Wednesday, 9 April 2008)

Your assignment is to convert the Candidates4 program using an ArrayList into a program using a TreeMap.

The "record" class Candidates and the field definitions class Fields need not change at all. You aren't doing anything to the inherent structure of the record that holds the data. Just copy and steal that.

The Main class will change only slightly. In the current Main class for Candidates4, the structure that is created to hold the data is the CandidatesList structure. You should change the name of this to something more appropriate, like CandidatesTreeMap, but this is simply syntactic sugar and doesn't do anything except match up names and symbols so the compiler can find things.

Also, because we don't need it any more, you can eliminate from the main program the small block of code that sorts the list and prints it in sorted order.

The major changes needed are in the class called CandidatesList class, which you should probably be renaming to be a CandidatesTreeMap class. The current code implements an ArrayList to store records of candidate data. You will need to change this in a bunch of places so that it implements a TreeMap for storing the data instead.

With an ArrayList the data is stored in the list in the order in which it is read in, and the data is accessed by running a for loop on the subscripted list of records. With a TreeMap, you will want to store the data using a key for storage and retrieval and the Candidate record as the "value" data to be stored.

With a TreeMap, you have to make sure that all the keys are unique. Since there is in fact a possibility that two candidates could have the same last name (this happened in Virginia about ten years ago when both the Rep and the Dem candidate for senator had the last name "Warner"), use the last name concatenated with the first name as the key for storage and retrieval. You should use last name plus first name and not the other way around to make sure that the records get stored sorted by last name first. (As opposed to the first name sort of the PhoneBook example on the website.)

The various methods for reading in the data, echoing the data, and printing records that match a particular value of a particular field will all change in the same way. The current code for an ArrayList walks down the list using the subscript. You should look at the PhoneBook example on the website and use the for loop structure there that will access the data in sorted order based on the key. Filtering the data based on matching the value is pretty much the same.

Notice one major change in the output by using the TreeMap that stores the data in sorted order by key. When using the unsorted ArrayList, when you printed records that matched a particular search string, you wound up printing the records in the order in which they had been read from the data and then stored. This may or may not have been in any sorted order. When you loop over keys, you read in sorted order of keys, so filtering to be able to print records that match a particular search string gives you the data sorted by key.

Since we don't need that code any more, you can delete the sortData method.

Upload to the dropbox as usual.

Lab Assignment 18

(Friday, 4 April 2008)

This lab will give you more practice with string manipulation and with input and output from files, and a little bit of work with modular arithmetic.

You are to implement a Caesar cipher program.

The main class should be the usual boilerplate Main that permits you to open an input file and an output file. The main method should then call a method doCipher that is passed the input data file Scanner and the output data file PrintWriter and does the actual work of doing the ciphering.

A Caesar cipher takes input text and shifts the text, letter by letter, based on a shift value. For example, if the shift value is 2, then each letter is shifted down in the alphabet by 2, with appropriate wraparound from Z to B, Y to A, etc.

For example, the word FOX becomes, with shift 4, JSB, with F shifting right four letters to become J, and so forth.

You may treat all the text as being case-insensitive.

The input should be a file that contains first an integer that is the shift number and then a sequence of words in a sentence.

The output should be a file (not just a console output) that contains the words in the sentence with the letters appropriately shifted.

You might want to try your input progrma on the data stored here.

Hint: You will need to use modular arithmetic to wrap the letter index back around from beyond Z or forward (in the case that the shift is negative). Note that this can be accomplished with
index = (index + shift + 26) % 26;
Since 26 is zero modulo 26, the addition of 26 inside the parentheses has no effect on the numerical result. However, if the shift is negative, so that index + shift might possibly turn out to be a negative number, adding in the 26 produces a positive number again. This makes it unnecessary for the programmer to figure out what the official rules are for the programming language (in this case Java) when one does a modular reduction on a negative number.

Lab Assignment 17

(Wednesday, 2 April 2008)

This exercise is the first part of the homework assignment that is due next Tuesday. In this lab assignment you will modify/write code that will allow you to read/write files and create a simple ArrayList.

Start with the code of the Candidates2 example from the class web site. Modify this code to read from the input data file for the Homework 7 assignment and to create an ArrayList of String values and then to echo that ArrayList to the console.

This is not a difficult assignment. However, you will not be able to read from a file and create and manipulate fields in a record in an ArrayList if you cannot first read from a file. The main purpose of this is to make sure that you can get the data into your program and that you have the file open and close stuff done right. That way, when you get to the point of doing the rest of the assignment, you can at least rely on the ability to get the data into your program.

Make sure you change any and all symbols referring to presidential candidates to now reflect the fact that this code is (or will be) dealing with checkbook records.

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Quiz 2

(Friday, 28 March 2008)

Section 4

The lab quiz for Section 4 can be found here.

Section 5

The lab quiz for Section 5 can be found here.

Section 6

The lab quiz for Section 6 can be found here.

Lab Assignment

(Wednesday, 26 March 2008)

No lab. Exams will be handed back and gone over.

Lab Assignment 16

(Friday, 21 March 2008)

Do problem 7.14, page 388 of the text. Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 15

(Wednesday, 19 March 2008)

Do problem 7.13, page 388 of the text. Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 14

(Friday, 7 March 2008)

Do program 7.15 on page 389 of the text. Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 13

(Wednesday, 5 March 2008)

Do program 7.16 on page 389 of the text. Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 12

(Friday, 29 February 2008)

Do program 6.15 on page 326 of the text. Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Note that this problem doesn't really have a set-up to it. You are to write a class that will take a robot home from some unknown location, but the set-up that puts the robot at that unknown location is not something we are going to provide you.

There are three main purposes of this exercise, then. First, you need to look up in the robots documentation to find out how a robot can find its location; this comes from using built-in functions in the robots package. Second, you will need to implement loops to get the robot home.

Most importantly, however, you will need to figure out how to test your program. Setting up tests and building the environment that allows you to test code is a very important part of getting a program correct.

Lab Assignment 11

(Wednesday, 27 February 2008)

This is to help you understood loops, as well as to get some practice in doing graphical display.

Do number 5.20 parts d) and f), pages 269-271, in your text.


I suggest you create a Main class with the following code

import javax.swing.*;
import java.awt.Color;
public class Main
{
  public static void main(String[] args)
  {
    DrawD myD = new DrawD();
    DrawF myF = new DrawF();
    JPanel contents = new JPanel();
    contents.add(myD);
    contents.add(myF);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(contents);
    frame.pack();
    frame.setVisible(true);
  }
}
and that you then create two classes, DrawD and DrawF, to draw the two graphic images. You should start with listing 5.7, pages 251-252, in the text as the boilerplate for the DrawD and DrawF classes, and your code should replace line 23 in that listing.


I strongly recommend that you do part f) first so you will be able to finish. This one is mostly just loop control with two for loops and an if in the middle to determine whether to use Color.Black or Color.White for the circles. I ALSO RECOMMEND FOR THIS PART OF THE ASSIGNMENT THAT YOU CHANGE the scaling of "11" in line 19 of listing 5.7 to a scaling of "15". Change both numbers 11 to be 15. This will make the circles slightly smaller and avoid some sizing annoyances I was unable to get around without extra effort. Note that you will have a separate scaling in your code for part d) from what you have in the code for part f), so you can do part f) at 15 and part d) at 11 as originally written in listing 5.7.

For part d), the hard part is going to be to the offsets correct. Note that the way the circle drawing works, you specify (page 98) the upper left corner and the length and width of a rectangle in which an ellipse is drawn. You can draw the nested circles, then, by running a loop that moves this upper left corner (both the x and the y coordinates) down and to the right, while making the size of the rectangle smaller with each step as well. One way to do this wrong will give you nested "circles" all centered at (0,0). It's all a matter of handling the offsets from (0,0).

As always, upload to the departmental drop box.

Lab Quiz 1

(Wednesday, 20 February 2008)

Section 4

The lab quiz for Section 4 can be found here.

Section 5

The lab quiz for Section 5 can be found here.

Section 6

The lab quiz for Section 6 can be found here.

Lab Assignment 10

I strongly

Lab Quiz 1

(Wednesday, 20 February 2008)

Section 4

The lab quiz for Section 4 can be found here.

Section 5

The lab quiz for Section 5 can be found here.

Section 6

The lab quiz for Section 6 can be found here.

Lab Assignment 10

I strongly

Lab Quiz 1

(Wednesday, 20 February 2008)

Section 4

The lab quiz for Section 4 can be found here.

Section 5

The lab quiz for Section 5 can be found here.

Section 6

The lab quiz for Section 6 can be found here.

Lab Assignment 10

(Friday, 15 February 2008)

Objective: Learn to develop an algorithm using if and while statements.

Do assignment 4.15 on page 210 of your text.

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 9

(Wednesday, 13 February 2008)

Do assignment 4.12 on page 209 of your text.

A suitable file for setting up the Walls and Things can be found at ShovelBotField.txt.

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 8

(Friday, 8 February 2008)

Do program 3.8 on page 162. As with the previous lab assignment, the basic idea here is that you should think about how to control a program and about the balance between doing only what is necessary in order to get the job done and writing a program that is easily understood and modifiable.

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 7

(Wednesday, 6 February 2008)

For this lab, we will focus on the concept of program refinement. Specifically, we should be thinking about how best to break a problem down into smaller pieces for proper flow of control.

Do problem 3.6 in the text.

Upload your .java files for the solution to the dropbox at https://www.cse.sc.edu.

Lab Assignment 6

(Friday, 1 February 2008)

Objectives: Learn how to do some simple graphics, and more with extensions of classes.

You are to do a version of problem 2.19, page 112. Specifically, do part a), choosing the Car icon. This is a relatively simple thing to do, although when I did it I had to fudge a little bit to get the front and back windows and the roof to line up properly.

Then do part b), using the Car icon as the icon for a robot. Create the robot at intersection (1,1), facing east, and then move the robot two intersections to the east. Note that the Car icon doesn't actually have a "front" that is different from the "rear".

Lab Assignment 5

(Wednesday, 30 January 2008)

Objectives: Learn how to extend methods.

Do problem 2.12 on page 110. Your main method should call a method tripleFlip that causes the robot to do the triple flip. The tripleFlip method should in turn call a method flip that causes the robot to do a single flip.

Your complete Diver class should thus have (at least) the constructor, the dive method, the tripleFlip method, and the flip method.

Note also that the requirements are that the robot finish facing up, and not down.

Lab Assignment 4

(Friday, 25 January 2008)

From Chapter 1 of your textbook, do problem 1.17 on page 51. This will require you to be able to read the online documentation. To get to the online documentation, just bring up a browser and google "java 6 jtextarea". (Note that this can be case-insensitive.)

Lab Assignment 3

(Wednesday, 23 January 2008)

Do problem 1.14, page 49, of the textbook.

Lab Assignment 2

(Friday, 18 January 2008)

The text for this assignment is quite long and is on a separate page.

Lab Assignment 1

(Wednesday, 16 January 2008)

The text for this assignment is quite long and is on a separate page.

Swearingen Engineering Center | Columbia, SC 29208 | 803.777.2880 | web@cse.sc.edu