This example demonstrates how to follow through the table example from Guzdial and Ericson's Data Structures book, pages 8-9, to a complete class definition plus a complete Java application that demonstrates it. A table is also called a matrix or array. The corresponding programming language facility is called the array.
Arrays are important to fully understand because 20th and early 21st century computer memory hardware operates very much like arrays. Computation speed is determined by exactly what happens in the computer hardware. So, people who know the difference between what make array-using programs faster or slower are able to apply that same knowledge to anything the computer does!
Here is the table displayed textually:
| Name | Age
|
Weight
|
| Arnold | 12
|
220.0
|
| Fozzie
|
38
|
125.0
|
| Kermit
|
47
|
3.0
|
| Ms. Piggy
|
42
|
54
|
Here is the .java file that defines the KidShowCharTable class:
public class KidShowCharTable
{
private String[] names;
private int[] ages;
private double[] weights;
public KidShowCharTable()
{
final int nChars = 4;
names = new String[nChars];
names[0] = "Arnond";
names[1] = "Fozzie";
names[2] = "Kermit";
names[3] = "Ms. Piggy";
ages = new int[nChars];
ages[0] = 12;
ages[1] = 38;
ages[2] = 47;
ages[3] = 42;
weights = new double[nChars];
weights[0] = 220.0;
weights[1] = 125.0;
weights[2] = 2.0;
weights[3] = 54.0;
}
public void print()
{
System.out.println("Name \tAge\tWeight");
for( int i = 0; i < names.length; i++ )
{
System.out.println(names[i] + "\t" + ages[i] + "\t" + weights[i]);
}
}
}
Here is the .java file that defines the KidShowCharTableDemonstrator class which contains the Java application that demonstrates the class:
public class KidShowCharTableDemonstrator
{
public static void main(String[] args)
{
KidShowCharTable myTable = new KidShowCharTable();
myTable.print();
}
}
(Pedagogical note: Besides giving practice with conditionals and methods as control structures, this programming problem covers the concept that information is recorded on media such as printed menus or computer memory at particular locations, locations are numerical, and the location is an efficient substitute for the information itself. )
Here is the menu:
| 1 | Chicken Chow Mein
|
4.25 |
| 2 | Shrimp Chow Mein
|
4.25 |
| 3 | Moo Goo Gai Pan
|
4.25 |
| 4 | Beef with Broccoli
|
4.25 |
| 5 | Sweet and Sour Pork
|
4.25 |
| 6 | Twice Cooked Pork
|
4.35 |
| 7 | Chicken with Peanuts
|
4.35 |
| 8 | Shrimp with Lobster Sauce
|
4.35 |
| 9 | Bean Curd with Garlic Sauce
|
4.35 |
| 10 | House Special Sliced Chicken
|
4.35 |
| 11 | Triple Delight (Shrimp, Roast Pork, Chicken with Mixed Vegetables.
|
4.95 |
| 12 | Chicken with Orange Flavor
|
4.95 |
| 13 | Beef with Orange Flavor
|
4.95 |
| 14 | Boneless Spare Ribs
|
4.95 |
| 15 | Bar-B-Q Spare Ribs
|
4.95 |
Observe that the items whose locations are 1 through 5 are priced at 4.25, the items in the next 5 locations 6 through 10 are at bit more expensive at 4.35, and the items in the last group of locations 11 through 15 are the most expensive at 4.95 each. The manager organized the menu that way so the following programming assignment will be easier for beginning students.
Write a program that enables the counter person to type in the location (1 through 15) of up to 5 items, and for each item, the number of servings in the order. The program should then reprint the order (in the same sequence it was typed in), the total of the prices in the order, the amount of the 5% restaurant tax and the total bill of the total of the prices plus the tax. The counter person will type 0 for the location when the customer finishes ordering. The order will also be finished after 5 items were given (because there is no room on the bill for more than 5 items.)
Here is an example run:
% java orderLunchPrintBill Next item(1-15) and quantity? (Type 0 0 to finish.) 1 3 Next item(1-15) and quantity? (Type 0 0 to finish.) 2 1 Next item(1-15) and quantity? (Type 0 0 to finish.) 12 2 Next item(1-15) and quantity? (Type 0 0 to finish.) 0 0 Thank you. Your order is: Item (LOCATION ON THE MENU) Quantity 1 3 2 1 12 2 Total for food: 27.00 Tax: 1.35 Total Bill: 28.35 %
The computer calculated 27.00 as 3*4.25+1*4.35+2*4.95. It calculated 1.35 as 27.00*0.05.
Programming strategy ONE:
(does not require conditional returns from method calls, is convenient to implement without method calls, and utilizes variables to track simulation state.)
Define 5 pairs of int variables, one pair for each of the possible 5 lines in the order. Also define a boolean variable named say orderInProgress initialized to true. Each time the program simulates the counter person asking the customer if he or she wants to order a different item, the program determines whether or not to set orderInProgress to false at that time. Subsequently, the program will use the value of orderInProgress to determine whether it will or will not simulate asking the customer for the information to put in the next line on the bill.
Programming strategy TWO:
(Uses more advanced programming concepts and elements, but not arrays).
Define a Bill class so that each instance of the class will simulate one bill. Define in the Bill class 5 pairs of int instance variables, one pair for each of the possible 5 lines in the order. You might name the first pair lineOneItemLoc and lineOneQuantity, the second pair lineTwoItemLoc and lineTwoQuantity, etc. up to lineFiveItemLoc and lineFiveQuantity. Program the constructor to initialize all 10 instance variables with 0.
Add to the class an instance method declared say public void take() to take the order. In the example above it printed and got the input shown in the first 4 lines. When the room on the bill is used up, or the LOCATION of the next item is zero, the take() method should return. That way, it will finish requesting a next item and quantity as soon as either the counter person entered 0 for an item LOCATION or entered the fifth item which filled up the space in the bill.
Add to the class an instance method declared say public void printOrder() to print the order in the form of the table composed of the 4 lines "Item (LOCATION..." through "12 2".
Add to the class a third instance method declared say public printTotals() that computes and prints the total for the food, and then the tax and finally the total bill amount. It takes care of printing the last three lines of the sample. The printTotals method should use conditionals such as if(lineOneItem <= 5) ...; else if(lineOneItem <= 10) ....; else ... ; to determine which of the three prices that apply.
Write a program that reads from a file of the daily closing values of say the Dow Jones stock average for a series of weeks. Specifically, each line of the file consists of 5 numbers, the daily closing average for Monday, Tuesday, Wednesday, Thursday and Friday, for a particular week. The program must then print, for each of the 5 days of the week, how many of the weeks had the peak occur at the close of that day.
The program must read each line of 5 values into a length 5 array. Here is a class framework for a solution [UNDER CONSTRUCTION!!]
import java.util.Scanner;
class PeakReporter
{
private Scanner sc;
private int oneWeekAverages[] = new int[5];
int nMonPeaks;
int nTuePeaks;
int nWedPeaks;
int nThuPeaks;
int nFriPeaks;
public PeakReporter(String filename)
{
sc = new Scanner();
oneWeekAverages[] = new int[5];
}
private boolean readOneLine()
{
try
{
for(int i=0; i < 5; i++)
oneWeekAverages[i] = sc.nextInt();
}
catch()
{
return false;
}
return true;
}
public void getReportData()
{
nMonPeaks = 0;
nTuePeaks = 0;
nWedPeaks = 0;
nThuPeaks = 0;
nFriPeaks = 0;
while( readOneLine() )
{
int dayOfThePeak = 0;
//WRITE THE CODE TO CALCULATE IN dayOfThePeak the index (0-4) in
//oneWeekAverages at which the peak occurred in the current week.
switch( dayOfThePeak )
{
case 0: nMonPeaks++; break;
case 1: nTuePeaks++; break;
case 2: nWedPeaks++; break;
case 3: nThuPeaks++; break;
case 4: nFriPeaks++; break;
}
}
public void printReport()
{
System.out.println("Day\t\tNumber of weeks when that day had the peak average");
System.out.print("Monday\t\t");
System.out.println(nMonPeaks);
System.out.print("Tuesday\t\t");
System.out.println(nTuePeaks);
System.out.print("Wednesday\t");
System.out.println(WedPeaks);
System.out.print("Thursday\t\t");
System.out.println(nThuPeaks);
System.out.print("Friday\t\t");
System.out.println(nFriPeaks);
}
}
For example, suppose the file contains:
10034 10056 10092 10021 10019 10021 10120 10119 10015 10002 9974 10003 9213 9410 9300
Notice that during the first week, the peak 10092 was on Wednesday and during the other two weeks, it was on Tuesday. After your program processes this data, it should print:
Day Number of weeks when that day had the peak average Monday 0 Tueday 2 Wednesday 1 Thursday 0 Friday 0
Refactor your solution to the above program so that an length 5 array named say nPeaksDaily is used instead of the five separately named, scalar variables nMonPeaks, nTuePeaks, nWedPeaks, nThuPeaks, and nFriPeaks. It should also use an array of String references for the names of the days, so your software is easier to internationalize. For example,
String namesOfDays[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
Finally, the lines of code that are repeated with minor changes for each day of the week, and the 5-way case statement, should be replaced by loops and code that uses an index into the nPeaksDaily array.
See Guzdial and Ericson's data structures book chapter 1 for the scenario described in English.
Here is the definition of the HuntSpot class:
public class HuntSpot
{
private String name;
private HuntSpot nextSpot;
HuntSpot(String x)
{
this.name = x;
}
void setNext(HuntSpot x)
{
this.nextSpot = x;
}
void startHunting()
{
if(nextSpot == null)
{
System.out.println("End of hunt at " + name);
}
else
{
System.out.println("Found a clue in " + name);
System.out.println("Will hunt in " + nextSpot.name);
nextSpot.startHunting();
}
}
}
Here is the definition of the TreasureHuntDemo class:
public class TreasureHuntDemo
{
public static void main(String[] args)
{
HuntSpot room1 = new HuntSpot("Katie's bedroom");
HuntSpot room2 = new HuntSpot("kitchen");
HuntSpot room3 = new HuntSpot("living room");
HuntSpot room4 = new HuntSpot("bathroom");
HuntSpot room5 = new HuntSpot("front porch");
room1.setNext(room2);
room2.setNext(room3);
room3.setNext(room4);
room4.setNext(room5);
room1.startHunting();
}
}
The treasure hunt is sequential. An array is sequential. Can we code the demonstration method using an array? Well, YES.
public class TreasureHuntDemo2
{
public static void main(String[] args)
{
HuntSpot array[] = {new HuntSpot("Katie's bedroom"),
new HuntSpot("kitchen"),
new HuntSpot("living room"),
new HuntSpot("bathroom"),
new HuntSpot("front porch")};
for(int i=0; i<array.length-1; i++)
{
array[i].setNext(array[i+1]);
}
array[0].startHunting();
}
}
The following class is a blueprint for objects each of which models a location that could be within a Picture.
Complete the methods that search a Picture for the location of a Pixel that is predominantly a particular color. Complete this program so it inputs the background Picture, locates up to three locations at which to copy new Pictures, and, for as many locations found, inputs and copies new Pictures.
Challenge: Figure out how the computer can distinguish a Pixel that is definitely red, green or blue in a Picture that may have noise due to .jpg lossy compression. Or, use a .png image for the background to avoid this problem.
public class Location
{
private int x;
private int y;
public Location(int xgiven, int ygiven)
{
this.x = xgiven;
this.y = ygiven;
}
public int getX()
{
return this.x;
}
public int getY()
{
return this.y;
}
}
Add to the following application class
/*
* This class uses the Guzdial and Ericson Multimedia Computing Book Classes
*/
public class PicturePlacer
{
/**
* @param args Not Used
*/
public static void main(String[] args)
{
FileChooser.pickMediaPath();
Picture backgroundPic = new Picture(FileChooser.pickAFile());
backgroundPic.explore();
Location locOfRed = findLocationWithRed(backgroundPic);
Location locOfGreen = findLocationWithGreen(backgroundPic);
Location locOfBlue = findLocationWithBlue(backgroundPic);
if(locOfRed != null)
{
Picture temp = new Picture(FileChooser.pickAFile());
copyPictureFromToWhere(temp,backgroundPic,locOfRed.getX(),locOfRed.getY());
}
if(locOfGreen != null)
{
Picture temp = new Picture(FileChooser.pickAFile());
copyPictureFromToWhere(temp,backgroundPic,locOfGreen.getX(),locOfGreen.getY());
}
if(locOfBlue != null)
{
Picture temp = new Picture(FileChooser.pickAFile());
copyPictureFromToWhere(temp,backgroundPic,locOfBlue.getX(),locOfBlue.getY }
backgroundPic.repaint();
}
/**
*
* @param from Picture to copy.
* @param to Picture to copy into.
* @param whereX X-location of where the upper left corner of the copy will be.
* @param whereY Y-location of where the upper left corner of the copy will be.
*/
public static void copyPictureFromToWhere(Picture from, Picture to,
int whereX, int whereY)
{
for(int x=0; x < from.getWidth(); x++)
{
if(x+whereX >= 0 && x+whereX < to.getWidth() )
{
for(int y=0; y < from.getHeight(); y++)
{
if(y+whereY >= 0 && y+whereY < to.getHeight())
{
to
.getPixel(x+whereX,y+whereY)
.setRed(from.getPixel(x,y).getRed());
to
.getPixel(x+whereX,y+whereY)
.setGreen(from.getPixel(x,y).getGreen());
to
.getPixel(x+whereX,y+whereY)
.setBlue(from.getPixel(x,y).getBlue());
}
}
}
}
}
public static Location findLocationWithRed(Picture p)
{
/* YOU FINISH THE CODE! */
int x = 0;
int y = 0;
if(true) return new Location(x,y);
else return null;
}
public static Location findLocationWithGreen(Picture p)
{
/* YOU FINISH THE CODE! */
int x = 0;
int y = 0;
if(true) return new Location(x,y);
else return null;
}
public static Location findLocationWithBlue(Picture p)
{
/* YOU FINISH THE CODE! */
int x = 0;
int y = 0;
if(true) return new Location(x,y);
else return null;
}
}
Here is a suitable sample background .png image:
Write a complete Java application that copies a number (say 4) pictures specified by the user from disk into memory, and then repeatedly, say 50 times, displays them in the same window sequentially, in their original order, producing an animation. It should use Guzdial and Ericson's book classes.
Resources:
The book classes and accompanying documentation: Download from http://coweb.cc.gatech.edu/mediaComp-plan/uploads/101/bookClasses-7-22-09.zip
Four .jpg image files for testing.

Lab. Notes:
Set the CLASSPATH environment variable so javac and java can find both the book classes and the files in the current directory we will use for the project:
export CLASSPATH=.:<book classes directory>
Programming Notes:
public class ArrayDemo
{
static final int NPICTURES = 4;
static final int NANIMRUNS = 50;
public static void main(String[] args)
{
System.out.println("Hello from ArrayDemo");
}
}
public class ArrayDemo
{
static final int NPICTURES = 4;
static final int NRUNS = 50;
public static void main(String[] args)
{
System.out.println("Hello from ArrayDemo");
Picture pframe = new Picture(400,400);
pframe.show();
}
}
public class ArrayDemo
{
static final int NPICTURES = 4;
static final int NRUNS = 50;
public static void main(String[] args)
{
System.out.println("Hello from ArrayDemo");
Picture pframe = new Picture(400,400);
pframe.show();
Picture p = new Picture(FileChooser.pickFile());
pframe.copyPicture(p);
pframe.repaint();
}
}
Study the following class definition:
class Counter
{
private int count;
public Counter()
{
this.count = 0;
}
public void addOne()
{
this.count = this.count + 1;
}
public int get()
{
return this.count;
}
public void print()
{
System.out.println("Counter's count is now "
+ this.get());
}
}
(1) Figure out the difference between these two application programs, besides their names. (2) What do each of these two application programs print when they are run?
class CopyTrickerOne
{
public static void main(String[] args)
{
Counter aCounter;
Counter anotherCounter;
aCounter = new Counter();
anotherCounter = new Counter();
aCounter = anotherCounter;
for(int i=0; i < 10; i++)
{
aCounter.addOne();
anotherCounter.addOne();
anotherCounter.addOne();
}
aCounter.print();
anotherCounter.print();
}
}
|
class CopyTrickerTwo
{
public static void main(String[] args)
{
Counter aCounter;
Counter anotherCounter;
aCounter = new Counter();
anotherCounter = new Counter();
for(int i=0; i < 10; i++)
{
aCounter.addOne();
anotherCounter.addOne();
anotherCounter.addOne();
}
aCounter = anotherCounter;
aCounter.print();
anotherCounter.print();
}
}
|
There has been error in communication with booki server. Not sure right now where is the problem.
You should refresh this page.