import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import java.awt.*;
// This file gives an example of doing simple
// graphical user interface (GUI) in Java using
// the Swing API.
//
// You can use this file as a template for the GUI
// part of your solution to Homework 2.
//
// The various classes involved are described
// briefly below. The main thing you need to
// modify (other than renaming classes) is the
// DemoPanel class, which is the GUI component
// that should display your tree.
public class GUIExample {
// The main method creates a frame object and
// displays it.
public static void main(String[] args) {
// you will put all preprocessing steps here
// display the frame window
DemoFrame frame = new DemoFrame("x", "y");
frame.setTitle("GUI Demonstration");
frame.show();
}
}
// Frame objects are movable frame windows; they
// can contain other GUI components like buttons,
// text areas, and panels. DemoFrame is a frame
// class that contains a panel; right now, the panel
// displays a hard-coded tree picture (see the
// class DemoPanel).
class DemoFrame extends JFrame {
private DemoPanel panel;
public DemoFrame(String str1, String str2) {
final int DEFAULT_FRAME_WIDTH = 300;
final int DEFAULT_FRAME_HEIGHT = 300;
// set the size of the frame window
setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
// create and install a "listener object"
// (event handler) to listen for window events
WindowCloser listener = new WindowCloser();
addWindowListener(listener);
// create a panel object and install it in
// the "content pane"
panel = new DemoPanel(str1, str2);
Container contentPane = getContentPane();
contentPane.add(panel, "Center");
}
// The class WindowCloser is a listener (event
// handler) class.
private class WindowCloser extends WindowAdapter {
// When the user closes the frame window, we
// kill the program.
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
}
// THIS IS THE CLASS YOU NEED TO MODIFY.
// Panel objects are GUI components that you
// can draw on. A panel object should store
// as instance data all the information it needs
// to repaint itself. In this simple example,
// objects of type DemoPanel just store a string
// called childName, which is used to draw a
// diagram of a small, hard-coded "tree".
class DemoPanel extends JPanel {
private String firstVar;
private String secondVar;
public DemoPanel(String str1, String str2) {
firstVar = str1;
secondVar = str2;
}
// The paintComponent method is called every time
// that the panel needs to be displayed or refreshed.
// Anything you want drawn on the panel should be drawn
// in this method. In this example, a small tree is
// "hard-coded". More typically, the panel could store
// a reference to an object with a graphical representation
// (like a tree), and we'd call an instance method of that
// object to get it to draw itself. Note: this method
// gets passed (as parameter "page") a reference to the
// current graphical context object of the GUI component;
// all drawing is done through the "page" reference.
public void paintComponent(Graphics page) {
// leave the next line in
super.paintComponent(page);
// replace this code with a method call that draws your tree
page.setColor(Color.green);
page.fillOval(ROOT_X, ROOT_Y, 2*RADIUS, 2*RADIUS);
page.fillOval(ROOT_X+H_SKIP, ROOT_Y+V_SKIP,
2*RADIUS, 2*RADIUS);
page.drawLine(ROOT_X+RADIUS,ROOT_Y+RADIUS,ROOT_X+H_SKIP+RADIUS,ROOT_Y+V_SKIP+RADIUS);
page.setColor(Color.black);
page.drawString(firstVar, ROOT_X + RADIUS - SPACE, ROOT_Y + RADIUS + SPACE);
page.drawString(secondVar, ROOT_X + H_SKIP + RADIUS - SPACE, ROOT_Y + V_SKIP + RADIUS + SPACE);
}
private static final int ROOT_X = 70;
private static final int ROOT_Y = 100;
private static final int V_SKIP = 60;
private static final int H_SKIP = 60;
private static final int RADIUS = 15;
private static final int SPACE = 3;
}
---------------------------
import java.io.*;
import java.util.*;
public class ID3 {
int numAttributes; // The number of attributes including the output attribute
String []attributeNames; // The names of all attributes. It is an array of dimension numAttributes. The last attribute is the output attribute
/* Possible values for each attribute is stored in a vector. domains is an array of dimension numAttributes.
Each element of this array is a vector that contains values for the corresponding attribute
domains[0] is a vector containing the values of the 0-th attribute, etc..
The last attribute is the output attribute
*/
Vector []domains;
/* The class to represent a data point consisting of numAttributes values of attributes */
class DataPoint {
/* The values of all attributes stored in this array. i-th element in this array
is the index to the element in the vector domains representing the symbolic value of
the attribute. For example, if attributes[2] is 1, then the actual value of the
2-nd attribute is obtained by domains[2].elementAt(1). This representation makes
comparing values of attributes easier - it involves only integer comparison and
no string comparison.
The last attribute is the output attribute
*/
public int []attributes;
public DataPoint(int numattributes) {
attributes = new int[numattributes];
}
};
/* The class to represent a node in the decomposition tree.
*/
class TreeNode {
public double entropy; // The entropy of data points if this node is a leaf node
public Vector data; // The set of data points if this is a leaf node
public int decompositionAttribute; // If this is not a leaf node, the attribute that is used to divide the set of data points
public int decompositionValue; // the attribute-value that is used to divide the parent node
public TreeNode []children; // If this is not a leaf node, references to the children nodes
public TreeNode parent; // The parent to this node. The root has parent == null
public TreeNode() {
data = new Vector();
}
};
/* The root of the decomposition tree */
TreeNode root = new TreeNode();
/* This function returns an integer corresponding to the symbolic value of the attribute.
If the symbol does not exist in the domain, the symbol is added to the domain of the attribute
*/
public int getSymbolValue(int attribute, String symbol) {
int index = domains[attribute].indexOf(symbol);
if (index < 0) {
domains[attribute].addElement(symbol);
return domains[attribute].size() -1;
}
return index;
}
/* Returns all the values of the specified attribute in the data set */
public int []getAllValues(Vector data, int attribute) {
Vector values = new Vector();
int num = data.size();
for (int i=0; i< num; i++) {
DataPoint point = (DataPoint)data.elementAt(i);
String symbol = (String)domains[attribute].elementAt(point.attributes[attribute] );
int index = values.indexOf(symbol);
if (index < 0) {
values.addElement(symbol);
}
}
int []array = new int[values.size()];
for (int i=0; i< array.length; i++) {
String symbol = (String)values.elementAt(i);
array[i] = domains[attribute].indexOf(symbol);
}
values = null;
return array;
}
/* Returns a subset of data, in which the value of the specfied attribute of all data points is the specified value */
public Vector getSubset(Vector data, int attribute, int value) {
Vector subset = new Vector();
int num = data.size();
for (int i=0; i< num; i++) {
DataPoint point = (DataPoint)data.elementAt(i);
if (point.attributes[attribute] == value) subset.addElement(point);
}
return subset;
}
/* Calculates the entropy of the set of data points.
The entropy is calculated using the values of the output attribute which is the last element in the array attribtues
*/
public double calculateEntropy(Vector data) {
int numdata = data.size();
if (numdata == 0) return 0;
int attribute = numAttributes-1;
int numvalues = domains[attribute].size();
double sum = 0;
for (int i=0; i< numvalues; i++) {
int count=0;
for (int j=0; j< numdata; j++) {
DataPoint point = (DataPoint)data.elementAt(j);
if (point.attributes[attribute] == i) count++;
}
double probability = 1.*count/numdata;
if (count > 0) sum += -probability*Math.log(probability);
}
return sum;
}
/* This function checks if the specified attribute is used to decompose the data set
in any of the parents of the specfied node in the decomposition tree.
Recursively checks the specified node as well as all parents
*/
public boolean alreadyUsedToDecompose(TreeNode node, int attribute) {
if (node.children != null) {
if (node.decompositionAttribute == attribute )
return true;
}
if (node.parent == null) return false;
return alreadyUsedToDecompose(node.parent, attribute);
}
/* This function decomposes the specified node according to the ID3 algorithm.
Recursively divides all children nodes until it is not possible to divide any further
I have changed this code from my earlier version. I believe that the code
in my earlier version prevents useless decomposition and results in a better decision tree!
This is a more faithful implementation of the standard ID3 algorithm
*/
public void decomposeNode(TreeNode node) {
double bestEntropy=0;
boolean selected=false;
int selectedAttribute=0;
int numdata = node.data.size();
int numinputattributes = numAttributes-1;
node.entropy = calculateEntropy(node.data);
if (node.entropy == 0) return;
/* In the following two loops, the best attribute is located which
causes maximum decrease in entropy
*/
for (int i=0; i< numinputattributes; i++) {
int numvalues = domains[i].size();
if ( alreadyUsedToDecompose(node, i) ) continue;
// Use the following variable to store the entropy for the test node created with the attribute i
double averageentropy = 0;
for (int j=0; j< numvalues; j++) {
Vector subset = getSubset(node.data, i, j);
if (subset.size() == 0) continue;
double subentropy = calculateEntropy(subset);
averageentropy += subentropy * subset.size(); // Weighted sum
}
averageentropy = averageentropy / numdata; // Taking the weighted average
if (selected == false) {
selected = true;
bestEntropy = averageentropy;
selectedAttribute = i;
} else {
if (averageentropy < bestEntropy) {
selected = true;
bestEntropy = averageentropy;
selectedAttribute = i;
}
}
}
if (selected == false) return;
// Now divide the dataset using the selected attribute
int numvalues = domains[selectedAttribute].size();
node.decompositionAttribute = selectedAttribute;
node.children = new TreeNode [numvalues];
for (int j=0; j< numvalues; j++) {
node.children[j] = new TreeNode();
node.children[j].parent = node;
node.children[j].data = getSubset(node.data, selectedAttribute, j);
node.children[j].decompositionValue = j;
}
// Recursively divides children nodes
for (int j=0; j< numvalues; j++) {
decomposeNode(node.children[j]);
}
// There is no more any need to keep the original vector. Release this memory
node.data = null; // Let the garbage collector recover this memory
}
/** Function to read the data file.
The first line of the data file should contain the names of all attributes.
The number of attributes is inferred from the number of words in this line.
The last word is taken as the name of the output attribute.
Each subsequent line contains the values of attributes for a data point.
If any line starts with // it is taken as a comment and ignored.
Blank lines are also ignored.
*/
public int readData(String filename) throws Exception {
FileInputStream in = null;
try {
File inputFile = new File(filename);
in = new FileInputStream(inputFile);
} catch ( Exception e) {
System.err.println( "Unable to open data file: " + filename + "\n" + e);
return 0;
}
BufferedReader bin = new BufferedReader(new InputStreamReader(in) );
String input;
while(true) {
input = bin.readLine();
if (input == null) {
System.err.println( "No data found in the data file: " + filename + "\n");
return 0;
}
if (input.startsWith("//")) continue;
if (input.equals("")) continue;
break;
}
StringTokenizer tokenizer = new StringTokenizer(input,",");
numAttributes = tokenizer.countTokens();
//System.out.println("numAttributes"+numAttributes);
if (numAttributes <= 1) {
System.err.println( "Read line: " + input);
System.err.println( "Could not obtain the names of attributes in the line");
System.err.println( "Expecting at least one input attribute and one output attribute");
return 0;
}
domains = new Vector[numAttributes];
for (int i=0; i < numAttributes; i++) domains[i] = new Vector();
attributeNames = new String[numAttributes];
for (int i=0; i < numAttributes; i++) {
attributeNames[i] = tokenizer.nextToken();
}
while(true) {
input = bin.readLine();
if (input == null) break;
if (input.startsWith("//")) continue;
if (input.equals("")) continue;
tokenizer = new StringTokenizer(input,",");
int numtokens = tokenizer.countTokens();
//System.out.println("numtokens"+numtokens);
if (numtokens != numAttributes) {
System.err.println( "Read " + root.data.size() + " data");
System.err.println( "Last line read: " + input);
System.err.println( "Expecting " + numAttributes + " attributes");
return 0;
}
DataPoint point = new DataPoint(numAttributes);
for (int i=0; i < numAttributes; i++) {
point.attributes[i] = getSymbolValue(i, tokenizer.nextToken() );
}
root.data.addElement(point);
}
bin.close();
return 1;
} // End of function readData
//-----------------------------------------------------------------------
/* This function prints the decision tree in the form of rules.
The action part of the rule is of the form
outputAttribute = "symbolicValue"
or
outputAttribute = { "Value1", "Value2", .. }
The second form is printed if the node cannot be decomposed any further into an homogenous set
*/
public void printTree(TreeNode node, String tab) {
int outputattr = numAttributes-1;
if (node.children == null) {
int []values = getAllValues(node.data, outputattr );
if (values.length == 1) {
System.out.println(tab + "\t" + attributeNames[outputattr] + " = \"" + domains[outputattr].elementAt(values[0]) + "\";");
return;
}
System.out.print(tab + "\t" + attributeNames[outputattr] + " = {");
for (int i=0; i < values.length; i++) {
System.out.print("\"" + domains[outputattr].elementAt(values[i]) + "\" ");
if ( i != values.length-1 ) System.out.print( " , " );
}
System.out.println( " };");
return;
}
int numvalues = node.children.length;
for (int i=0; i < numvalues; i++) {
System.out.println(tab + "if( " + attributeNames[node.decompositionAttribute] + " == \"" +
domains[node.decompositionAttribute].elementAt(i) + "\") {" );
printTree(node.children[i], tab + "\t");
if (i != numvalues-1) System.out.print(tab + "} else ");
else System.out.println(tab + "}");
}
}
/* This function creates the decision tree and prints it in the form of rules on the console
*/
public void createDecisionTree() {
decomposeNode(root);
printTree(root, "");
}
/* Here is the definition of the main function */
public static void main(String[] args) throws Exception {
int num = args.length;
if (num != 1) {
System.out.println("You need to specify the name of the datafile at the command line " );
return;
}
ID3 me = new ID3();
long startTime = System.currentTimeMillis(); // To print the time taken to process the data
int status = me.readData(args[0]);
if (status <= 0) return;
me.createDecisionTree();
long endTime = System.currentTimeMillis();
long totalTime = (endTime-startTime)/1000;
System.out.println( totalTime + " Seconds");
}
/* End of the main function */
}
----------------------------------------
Sunday, March 29, 2009
Thursday, March 26, 2009
Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class TestQueueIntSimple extends JPanel implements ActionListener{
// initialize the class variables,access specifier are using private
private JLabel labelt;
private JFrame frame;
private JPanel panel;
//private JLabel labelmid;
private JLabel putvalueLable;
private JLabel takenvalueLable;
private JLabel queuedepthLable;
private JLabel errormsgLable;
private JTextField putvalue;
private JTextField takenvalue;
private JTextField queuedepth;
public JTextField errormsg;
private JButton button;
private JButton button2;
private JButton button3;
private JTextArea tarea;
private JScrollPane scrollpane;
QueueIntSimple qs = new QueueIntSimple();
public TestQueueIntSimple(){
frame= new JFrame(" -- Queue Implemantion -- ");
frame.getContentPane().setLayout(null);
putvalueLable = new JLabel("Enter value to put");
putvalue = new JTextField(15);
takenvalueLable = new JLabel("Value taken");
takenvalue = new JTextField(15);
queuedepthLable = new JLabel("Queue depth");
queuedepth = new JTextField(15);
labelt = new JLabel("Queue Implemantion");
labelt.setFont(new Font("Serif", Font.BOLD, 25));
errormsgLable = new JLabel("Error messages");
errormsg = new JTextField(15);
button = new JButton("PUT");
button2 = new JButton("TAKE");
button3 = new JButton("DISPLAY");
tarea = new JTextArea();
labelt.setBounds(250,20,350,70);
putvalueLable.setBounds(50,70,150,70);
takenvalueLable.setBounds(50,120,150,70);
putvalue.setBounds(220,90,60,27);
takenvalue.setBounds(220,140,60,27);
queuedepthLable.setBounds(50,170,150,70);
queuedepth.setBounds(220,190,60,27);
errormsgLable.setBounds(50,220,150,70);
errormsg.setBounds(220,240,180,27);
button.setBounds(100,280,80,27);
button2.setBounds(200,280,80,27);
button3.setBounds(300,280,120,27);
tarea.setBounds(220,320,180,180);
frame.getContentPane().add(labelt);
frame.getContentPane().add(putvalueLable);
frame.getContentPane().add(putvalue);
frame.getContentPane().add(takenvalueLable);
frame.getContentPane().add(takenvalue);
frame.getContentPane().add(queuedepthLable);
frame.getContentPane().add(queuedepth);
frame.getContentPane().add(errormsgLable);
frame.getContentPane().add(errormsg);
frame.getContentPane().add(button);
frame.getContentPane().add(button2);
frame.getContentPane().add(button3);
frame.getContentPane().add(tarea);
button.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
frame.setSize(550,550);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event){
if(event.getSource() == button)
{
int value = Integer.parseInt(putvalue.getText());
if(qs.queueDepth() == 5){
errormsg.setText("Queue is full");
}
qs.putValue(value);
queuedepth.setText(qs.queueDepth()+"");
}else if(event.getSource() == button2){
if(qs.queueDepth() == 0){
errormsg.setText("Queue is empty");
}
takenvalue.setText(qs.takenValue()+"");
queuedepth.setText(qs.queueDepth()+"");
System.out.println("vvvvv"+qs.queueDepth());
}else if(event.getSource() == button3){
tarea.setText(qs.toString());
}
}
public static void main(String arg[]){
TestQueueIntSimple tqs = new TestQueueIntSimple();
}
}
----------------------------------
public class QueueIntSimple {
private int queue[]; //array in int
private int capacity; //capacity of the queue
private int count; //indicates number of elements currently stored in the queue
// elements[0] is front, elements[count-1] is back
public QueueIntSimple() {
queue = new int[5];
capacity =5;
}
public int getSize() { return count; }
public boolean isEmpty() { return count==0; }
public boolean isFull() { return count == capacity; }
public void putValue(int value) {
if(isFull()) {
System.out.println("Queue is full");
return;
}
System.out.println("Inserting " + value + " at Queue[" + count + "]");
queue[count++]=value;
}
public int poll() {
if(isEmpty()) {
System.out.println("Poll:Queue is empty");
}
return queue[0];
}
public int takenValue() {
int item = poll();
count--;
// shift elements up
for(int i=0; i
}
return item;
}
public int queueDepth() {
int depth = 0;
for(int i=0; i<5; i++) {
if(0< queue[i]){
depth++;
}
}
return depth;
}
public String toString() {
String s = "";
for(int i = 0; i
s =s+"Queue["+i+"] : "+queue[i]+"\n";
}
}
return s;
}
public static void main(String ar[]){
QueueIntSimple qs = new QueueIntSimple();
qs.putValue(4);
qs.putValue(2);
qs.putValue(1);
System.out.println(qs.toString());
qs.takenValue();
System.out.println(qs.toString());
}
}
Solution for table
Movies
Theater Date Time Capacity DisplayType Title Length Rating
1 25-Feb-08 7:00 PM 300 Digital Data Projector 27 Dresses 01:47 PG-13
1 25-Feb-08 9:00 PM 300 Digital Data Projector 27 Dresses 01:47 PG-13
1 25-Feb-08 11:00 PM 300 Digital Data Projector 27 Dresses 01:47 PG-13
2 25-Feb-08 7:00 PM 200 Film Projector Welcome Home Roscoe Jenkins 01:54 PG-13
2 25-Feb-08 9:15 PM 200 Film Projector Welcome Home Roscoe Jenkins 01:54 PG-13
2 25-Feb-08 11:30 PM 200 Film Projector Welcome Home Roscoe Jenkins 01:54 PG-13
3 25-Feb-08 5:00 PM 150 Digital Data Projector 27 Dresses 01:47 PG-13
3 25-Feb-08 7:00 PM 150 Digital Data Projector 27 Dresses 01:47 PG-13
3 25-Feb-08 9:00 PM 150 Digital Data Projector Chronicles of Riddick 01:37 PG
3 25-Feb-08 11:00 PM 150 Digital Data Projector Chronicles of Riddick 01:37 PG
4 25-Feb-08 6:30 PM 200 Film Projector No Country for Old Men 02:02 R
4 25-Feb-08 9:00 PM 200 Film Projector No Country for Old Men 02:02 R
4 25-Feb-08 11:30 PM 200 Film Projector No Country for Old Men 02:02 R
5 25-Feb-08 7:00 PM 250 Digital Data Projector Welcome Home Roscoe Jenkins 01:54 PG-13
5 25-Feb-08 10:00 PM 250 Digital Data Projector No Country for Old Men 02:02 R
1 26-Feb-08 7:00 PM 300 Digital Data Projector Jumper 01:28 PG-13
1 26-Feb-08 8:45 PM 300 Digital Data Projector Jumper 01:28 PG-13
etc…
----------------------------
Books
ISBN Title Author1 Author2 Author3
1879389873 Learn UNIX in 28 days Jones, Mary Smith, Frank
8737734222 The Civil War: Brother Against Brother Templeton, Hank Templeton, Frank
9873483122 Database Security and Encryption Johnson, Fred Lee, Kirby Neeves, Whitney
1298834831 The Future of Planet Earth Scotten, Raymond
etc…
Theater Date Time Capacity DisplayType Title Length Rating
1 25-Feb-08 7:00 PM 300 Digital Data Projector 27 Dresses 01:47 PG-13
1 25-Feb-08 9:00 PM 300 Digital Data Projector 27 Dresses 01:47 PG-13
1 25-Feb-08 11:00 PM 300 Digital Data Projector 27 Dresses 01:47 PG-13
2 25-Feb-08 7:00 PM 200 Film Projector Welcome Home Roscoe Jenkins 01:54 PG-13
2 25-Feb-08 9:15 PM 200 Film Projector Welcome Home Roscoe Jenkins 01:54 PG-13
2 25-Feb-08 11:30 PM 200 Film Projector Welcome Home Roscoe Jenkins 01:54 PG-13
3 25-Feb-08 5:00 PM 150 Digital Data Projector 27 Dresses 01:47 PG-13
3 25-Feb-08 7:00 PM 150 Digital Data Projector 27 Dresses 01:47 PG-13
3 25-Feb-08 9:00 PM 150 Digital Data Projector Chronicles of Riddick 01:37 PG
3 25-Feb-08 11:00 PM 150 Digital Data Projector Chronicles of Riddick 01:37 PG
4 25-Feb-08 6:30 PM 200 Film Projector No Country for Old Men 02:02 R
4 25-Feb-08 9:00 PM 200 Film Projector No Country for Old Men 02:02 R
4 25-Feb-08 11:30 PM 200 Film Projector No Country for Old Men 02:02 R
5 25-Feb-08 7:00 PM 250 Digital Data Projector Welcome Home Roscoe Jenkins 01:54 PG-13
5 25-Feb-08 10:00 PM 250 Digital Data Projector No Country for Old Men 02:02 R
1 26-Feb-08 7:00 PM 300 Digital Data Projector Jumper 01:28 PG-13
1 26-Feb-08 8:45 PM 300 Digital Data Projector Jumper 01:28 PG-13
etc…
----------------------------
Books
ISBN Title Author1 Author2 Author3
1879389873 Learn UNIX in 28 days Jones, Mary Smith, Frank
8737734222 The Civil War: Brother Against Brother Templeton, Hank Templeton, Frank
9873483122 Database Security and Encryption Johnson, Fred Lee, Kirby Neeves, Whitney
1298834831 The Future of Planet Earth Scotten, Raymond
etc…
Wednesday, March 25, 2009
Solution


Lab1– Queue Data Structure
You have now used the stack class as part of your lab work. The stack concept is a very common algorithm which uses the inventory concept of last in first out (LIFO). The last item pushed onto the stack is the first item popped off the stack.
One implementation of the Queue problem is shown in the Queue Example folder. Create a command prompt window and type java TestQueue. Notice how read-only JTextFields are grayed out so that the user cannot write into those objects. Also notice that pressing the ENTER key when entering data creates an event which does the same as pressing the Button object. This makes entering data very fast into the GUI.
Another useful algorithm would be a class that would provide an inventory of first in first out (FIFO) commonly called a queue.
Here is an example of FIFO which follows the diagrams above:
1. Put a 5
2. Put a 45
3. Put a 12
4. Take a 5
5. Take a 45
6. Take a 12
7. FIFO inventory empty
Note the first item 5 is the first item to be removed.
The assignment is to create a queue class which incorporates the FIFO storage method. You might consider the stack class as a starting model. If you did that you would be able to use the concept of a put() which would be similar to the push() from the stack class but the creation of a take() would be very different than the pop() from the stack class. The take(), to duplicate the above pictorial example, would take the bottom item and then need to shift all the current inventory down one cell and reduce the depth of the inventory by one.
The queue will be only a maximum of five deep for ease of testing and will only store integers.
Of course, be sure to provide the ability to not over flow the inventory system or to protect from taking data from an empty inventory system.
Create a test Java GUI application to test the above class. Give the user the ability to Put into the queue, Take from a queue or Display the current contents of the queue. There should be confirming data indicating the number of items currently in the stack after each put() or take(). There should be a message generated if the stack is overflowed or empty.
The project should have a file containing the class QueueIntSimple, a file containing the extended Application class to test the class (e.g. TestQueueIntSimple). Don’t forget to supply proof of your program as part of what you turn in.
The GUI applet or application might look like the follow diagram:
Note 1 – the use of a “Display Queue” button, that each time pressed will display the current contents of the queue as text in the window frame as shown.
Note 2 – the Queue class should be a non-GUI application that provides only the behavior specified above. The Test Queue class should be the GUI application designed to test the Queue class. It can also contain the main() method required by all Java applications.
LAB 2 This would be an expansion of the FIFO class design of Lab 5. Here you would consider two types of data to be stored in inventory; one type of data would have a higher priority. The higher priority data would be retrived on a FIFO basis before standard data is retrived.
There are several design approches to this problem. A couple are discussed here. The first is to create two queues, one to hold the standard priority data and a second queue to hold the high priority data. The second method would use only one queue and place data at the end of the queue if standard data or to insert the high priority data at the proper location in the queue.
The first method is based on removing data from the beginning of the high priory queue if there is any data there before removing data from the standard priority queue. The put processes would place data at the end of each appropreate queue. From the user’s perspective, there is only a single queue with two priorities when implementing this approach.
With the second method there might be a put_high() method would place data ahead of data placed with put(). Of course put_high() data would not be placed ahead of other put_high() data already in inventory. The take() method would still take data from the beginning of the array, no matter what type of data. You might consider the need to keep track of both the total count in inventory as well as the count_high of total number of high priority data items in inventory
The queue(s) will be only ten deep for ease of testing and will only store integers. Design note – a total of 10 items can be stored in the data queue at any one point in time independent of the implementation choice chosen. The 10 items could be all high-priority data, all low-priority data or any combination of the two.
The project should have a file(s) containing the class(es), a file containing the test program to demonstrate the developed class(es). Don’t forget to supply proof of your program as part of what you turn in. Remember that Alt button with Prnt Scrn button captures the active window to the Windows clip board memory for pasting in a program like Word.
Lab 3 The instructor recommends invoking the example in the “Inheritance Example” folder – java TestEmployee.
The following will be the inheritance for the Employee class:
The Person class will have the data String for name and a means to get and set the name. The Employee class will extend from Person and add the capabilities to have an employee number as an int and an employee salary as a double.
Create an array of 100 Employees. Then create a user interface that will display a means for entering in the data and then saving the data to one of the Employee array objects. The “Save Employee” button will save the data to the array. The “Forward” and “Back” button will allow the user to move and display the current data in each array object. The “Clear Employee” button will allow the users to null out the String for the name, and set the salary and employee number to zero.
The project should have a file(s) containing the class(es), a file containing the test program to demonstrate the developed class(es). Don’t forget to supply proof of your program as part of what you turn in. Remember that Alt button with Prnt Scrn button captures the active window to the Windows clip board memory for pasting in a program like Word.
EXTRA CREDIT
Lab Simple inheritance program. Refer to the Test.java code below and run the Java console application found in FirstLookAnimals.
The Unified Modeling Language (UML) notation to represent inheritance is an arrow from the derived class to the base class as shown in th above diagram.
A very simple start to understanding polymorphism will be found in the subdirectory to this lab called Shapes. Go take a look.
The following code is the starting code for the test program. Please add the ability to supply how many animals to create rather that my hard coded 10. Also give the user the opportunity to loop to select another number of animals to create. The Test.java program should also be converted from a console to GUI application.
//Test.java
//FirstLook at inheritance.
//Thing.java, Animal.java, Dog.java, Cat.java, Rabbit.java
//and Test.java make up this first simple example.
public class Test extends Object
{
public static void main( String args[] )
{
System.out.println( "Welcome to simple inheritance Test!" );
Animal barnyard[];
barnyard = new Animal[10];//cannot use Thing as it cannot speak()
for( int z = 0; z < 10; z++)//proof of dynamic binding at run time!!!!
{ //10 could be a variable selected by user
//fewer selections as Animal cannot be used
int selection = ( int ) ( Math.random() * 4 );//0 through 3
switch( selection )
{
case 0:
barnyard[z] = new Dog(); //child to parent
break;
case 1:
barnyard[z] = new Cat(); //child to parent
break;
case 2:
barnyard[z] = new Rabbit();//child to parent
break;
case 3:
barnyard[z] = new Animal();//parent to parent
break;
}//end switch
}//end for
for( int z = 0; z < 10; z++)
{
barnyard[z].name();
barnyard[z].speak();
}//end for
System.out.println();
}//end main
}//end Test class
/* proof
Welcome to simple inheritance Test!
Cat Meow
Dog Woof
Animal Blank
Cat Meow
Animal Blank
Animal Blank
Rabbit Wiggle Nose
Animal Blank
Cat Meow
Rabbit Wiggle Nose
*/
You are to write the classes that support the above Test.java program and produce a proof similar to that shown above. The classes in the project will be Thing, Animal, Cat, Rabbit and Dog. You must write the Animal, Cat, Rabbit, Dog and revise Test.
The Thing class extends Object. The Animal class extends Thing. Finally, Cat, Rabbit and Dog extend Animal.
I will start you out with the code for Thing.
//Thing.java
public class Thing extends Object
{
public void name()
{
System.out.print("\nThing");
}
}//end Thing
You will need to add the ability to speak() to each of the other classes, which can be simply a System.out.print("\nWoof"); if it was the Dog class, for example.
Here is a suggested window:
Every time you press the Display button you generate the selected number of animal types. Place the output in a scrolling text area. Add number in front of the animal types to keep track of what is happening to the output.
Saturday, January 10, 2009
how to share reliance wimax internet connection
I am using Reliance Broadband Wimax internet connection and I got Static IP. But this is allowing only one PC to access the internet at one time. but I want to access through LAN with D-Link 8 port switch without using another Lan Card or Wireless router ...................... Can u please help me
Subscribe to:
Posts (Atom)