Wednesday, October 21, 2009
Binary Search tree using in Java
private BSTNode root;
public BinarySearchTree_temp(){
this(null);
}
public BinarySearchTree_temp(BSTNode node){
root = node;
}
public BSTNode getRoot(){
return root;
}
public BSTNode find(Comparable val){
if(root != null){
return root.findNode(val);
}
return null;
}
public BSTNode removeNode(Comparable val){
return removeNode(new BSTNode(val));
}
public BSTNode removeNode(BSTNode node){
return removeNodeHelper(root, node);
}
private BSTNode removeNodeHelper(BSTNode start, BSTNode node){
if(start == null){
return null;
}
else{
int delta = node.getValue().compareTo(start.getValue());
if(delta <> 0){
return removeNodeHelper(start.getRightChild(), node);
}
else{
if(start.isLeaf()){
return this.removeLeaf(start);
}
else if(start.isTree()){
return this.removeTree(start);
}
else{
return this.removeOneSubTree(start);
}
}
}
}
private BSTNode removeLeaf(BSTNode leaf){
if(leaf.hasParent()){
BSTNode leafParent = leaf.getParent();
leaf.setParent(null);
if(leafParent.hasLeftChild() && leafParent.getLeftChild().equals(leaf)){
leafParent.setLeftChild(null);
}
else{
leafParent.setRightChild(null);
}
}
else{
root = null;
}
return leaf;
}
private BSTNode removeTree(BSTNode tree){
BSTNode replacementNode;
if(heightHelper(tree.getLeftChild()) > heightHelper(tree.getRightChild())){
replacementNode = getMaxHelper(tree.getLeftChild());
}
else{
replacementNode = getMinHelper(tree.getRightChild());
}
if(tree.hasParent()){
if(tree.hasRightChild() && !tree.getRightChild().equals(replacementNode)){
replacementNode.setRightChild(tree.getRightChild());
}
if(tree.hasLeftChild() && !tree.getLeftChild().equals(replacementNode)){
replacementNode.setLeftChild(tree.getLeftChild());
}
BSTNode treeParent = tree.getParent();
if(treeParent.hasLeftChild() && treeParent.getLeftChild().equals(tree)){
treeParent.setLeftChild(replacementNode);
}
else{
treeParent.setRightChild(replacementNode);
}
BSTNode replaceNodeParent = replacementNode.getParent();
if(replaceNodeParent.hasLeftChild()
&& replaceNodeParent.getLeftChild().equals(replacementNode)){
replaceNodeParent.setLeftChild(null);
}
else{
replaceNodeParent.setRightChild(null);
}
replacementNode.setParent(treeParent);
}
else{
BSTNode replaceNodeParent = replacementNode.getParent();
if(replaceNodeParent.hasLeftChild()
&& replaceNodeParent.getLeftChild().equals(replacementNode)){
replaceNodeParent.setLeftChild(null);
}
else{
replaceNodeParent.setRightChild(null);
}
replacementNode.setParent(null);
replacementNode.setRightChild(tree.getRightChild());
replacementNode.setLeftChild(tree.getLeftChild());
tree.getRightChild().setParent(replacementNode);
tree.getLeftChild().setParent(replacementNode);
root = replacementNode;
}
tree.setParent(null);
tree.setRightChild(null);
tree.setLeftChild(null);
return tree;
}
private BSTNode removeOneSubTree(BSTNode start){
if(start.hasParent()){
BSTNode startParent = start.getParent();
if(startParent.hasLeftChild() && startParent.getLeftChild().equals(start)){
BSTNode n = start.hasLeftChild()? start.getLeftChild(): start.getRightChild();
n.setParent(startParent);
startParent.setLeftChild(n);
}
else{
BSTNode n = start.hasLeftChild()? start.getLeftChild(): start.getRightChild();
n.setParent(startParent);
startParent.setRightChild(n);
}
}
else{
if(start.hasLeftChild()){
root = start.getLeftChild();
start.getLeftChild().setParent(null);
}
else{
root = start.getRightChild();
start.getRightChild().setParent(null);
}
}
start.setLeftChild(null);
start.setRightChild(null);
start.setParent(null);
return start;
}
public void insertNode(BSTNode node){
if(root != null){
root.insertNode(node);
}
}
private BSTNode getMaxHelper(BSTNode node){
// if this node has a right child, it is not the maximum
// return the helper function executed on the right child
if(node.hasRightChild()){
return getMaxHelper(node.getRightChild());
}
return node;
}
private BSTNode getMinHelper(BSTNode node){
if(node.hasLeftChild()){
return getMinHelper(node.getLeftChild());
}
return node;
}
public boolean isEmpty(){
return root == null;
}
public void makeEmpty(){
root = null;
}
public int getHeigth(){
return heightHelper(root);
}
private int heightHelper(BSTNode start){
if (start == null){
return 0;
}
else{
return Math.max(heightHelper(start.getLeftChild()), heightHelper(start.getRightChild())) + 1;
}
}
public String toString(){
if(root == null)
return "{EmptyTree}\n";
else
return "\n" + showSub(root, 1) + "\n";
}
private String showSub(BSTNode node, int level){
StringBuffer sb = new StringBuffer();
if(node != null){
sb.append(showSub(node.getRightChild(), level+1));
for(int j = 0; j < tree =" new" tree =" new" i =" 0;" i =" 0;" hash =" 0;" value =" elem;" left =" lf;" right =" rt;" left =" node;" right =" node;" parent =" node;" left ="="" right ="="" delta =" node.getValue().compareTo(value);" left ="="" left =" node;"> 0){
if(right == null){
right = node;
right.setParent(this);
}
else{
right.insertNode(node);
}
}
}
public BSTNode findNode(Comparable val){
int delta = val.compareTo(value);
if(delta <> 0){
return (right != null)? right.findNode(val): null;
}
return this;
}
public BSTNode findNode(BSTNode node){
return findNode(node.getValue());
}
public boolean equals(Object o){
if(o instanceof BSTNode){
BSTNode b = (BSTNode) o;
return b.value.equals(value);
}
return false;
}
public int hashCode(){
if(hash == 0){
hash = value.hashCode();
}
return hash;
}
public String toString(){
return "{" + value.toString() + "}";
}
}
Monday, October 19, 2009
Grade Calculation and Credit card approval program in java
Grade Calculation
________________________________________
Problem Statement :
Write a program to calculate average test grades for a class. The number of tests per students and the number of students in the class must be variable. That means that your program should accept any number of tests or students (as input data) without any changes in the source code (look at examples below). Other input data will be student names and their test grades. Run the program using examples given below, and at least one of your own.
Interactive Session Example:
(prompt ‘>’ denotes output provided by your program (to distinguish it from user provided data – it should not be printed by your program) :
Example 1 :
>ENTER NUMBER OF STUDENTS IN THE CLASS :
3
>ENTER NUMBER OF TESTS PER STUDENT :
3
>ENTER THE NAME OF STUDENT NUMBER 1 :
BROWN
>ENTER GRADE 1 :
50
>ENTER GRADE 2 :
60
>ENTER GRADE 3 :
70
>
>*******************************************
>* THE FINAL GRADE FOR STUDENT BROWN IS 60 *
>*******************************************
>
>ENTER THE NAME OF STUDENT NUMBER 2 :
JONES
>ENTER GRADE 1 :
70
>ENTER GRADE 2 :
80
>ENTER GRADE 3 :
90
>
>*******************************************
>* THE FINAL GRADE FOR STUDENT JONES IS 80 *
>*******************************************
>
>ENTER THE NAME OF STUDENT NUMBER 3 :
RITT
>ENTER GRADE 1 :
50
>ENTER GRADE 2 :
70
>ENTER GRADE 3 :
90
>
>*******************************************
>* THE FINAL GRADE FOR STUDENT RITT IS 70 *
>*******************************************
>END.
Example 2:
>ENTER NUMBER OF STUDENTS IN THE CLASS :
2
>ENTER NUMBER OF TESTS PER STUDENT :
4
>ENTER THE NAME OF STUDENT NUMBER 1 :
CLOVER
>ENTER GRADE 1 :
50
>ENTER GRADE 2 :
60
>ENTER GRADE 3 :
70
>ENTER GRADE 4 :
80
>
>********************************************
>* THE FINAL GRADE FOR STUDENT CLOVER IS 65 *
>********************************************
>
>ENTER THE NAME OF STUDENT NUMBER 2 :
MOLKS
>ENTER GRADE 1 :
70
>ENTER GRADE 2 :
80
>ENTER GRADE 3 :
90
>ENTER GRADE 4 :
100
>
>*******************************************
>* THE FINAL GRADE FOR STUDENT MOLKS IS 85 *
>*******************************************
>END.
ASSIGNMENT 6
Assignment #6
Credit 2
________________________________________
Problem Statement :
Part 1
Write a program that will process one application for credit card KREDA. The following data has to be provided as input :
Data Acceptable Range
-------------------------------------------
age >0 and <200
name
monthly income > 0
credit rating "good"' or "bad"
house owner "yes" or "no"
permanent job "yes" or "no"
Remember to use prompt messages when asking for input. You do not have to check for acceptable range at this point.
Approval conditions :
• nobody under 16 can get the card.
• everybody over (or exactly) 16 who has a good credit will have their applications approved.
• for those that do not meet the above condition, application will be approved if they own the house.
• for those that do not meet the above condition, application will be approved if they have a permanent job, and their monthly income is over $3000.00.
• all others will have their application denied.
Example of the program output :
(This is only the final output, interactive session that you will need in order to get the data is omitted)
>*****************************
>
> KREDA CARD APPLICATION
>
> Name : Hughes Howard
> Age : 153
> Monthly Income : $100000
> Credit Rating : GOOD
> Owns House : YES
> Has Permanent Job : NO
>
> ***********************
> *APPLICATION APPROVED *
> ***********************
Part 2
Once you are sure that the program is making correct approval decisions extend it in the following way :
• check if all input data is valid
• after an application is processed, ask if there is another one and loop until there is none left.
at the end print the percentage of approved applications.
• make up your own example (it should include at least 3 passes through the loop, some approved and some non-approved applications).
ASSIGNMENT 7
Assignment #7
Grades 2
________________________________________
Problem Statement :
Write a program that will read student names and percentage grades frome the keyboard and then sort them (highest grade first) and calculate average, lowest and highest grade as shown below:
Example :
>How many students do you want to process?
4
>Enter name for student #1 :
JONES
>Enter grade for student #1 :
60
>Enter name for student #2 :
SMITH
>Enter grade for student #2 :
80
>Enter name for student #3
FORSTER:
>Enter grade for student #3 :
55
>Enter name for student #4 :
ALAZAR
>Enter grade for student #4 :
85
>====================
>CLASS GRADE REPORT :
>____________________
>ALAZAR B
>SMITH B
>JONES D
>FORSTER F
>_____________________
>HIGHEST GRADE : 80.00
>LOWEST GRADE : 55.00
>AVERAGE : 70.00
>=====================
ASSIGNMENT 8
________________________________________
Write a menu driven program that implements the following Binary Search Tree Operations
• FIND (item)
• INSERT (item)
• DELETE (item)
• DELETE_TREE (delete all nodes - be careful with the traversal!)
ASSIGNMENT 9
Write a program that finds the max binary tree height. (This is an extremely short piece of code!)
Sunday, October 11, 2009
Basic web application in Html and Java
1. The Java programming language features (for example, portable, platform independent, …) and describe how Java is used in IT industry. (Get information from the book and Internet). Use at least 300 words in your .html to explain the features of Java and at least 300 words to explain how Java is used in IT industry.
2. Features of Java applications and the components. Use a program that you worked before to explain. You will have a link to show the source code, also use at least 300 words in your .html to explain Java application, its components, the control flow in your sample program and how it works, as if you are a Java tutor teaching a beginner. As you teach, you reinforce your understanding.
3. Features of Java applets and the components. Give at lease one example. Provide a link to let the user to run your applet, also, provide a link called “Source Code”, like Sun’s web site (http://java.sun.com/applets/jdk/1.4/index.html) , so that the user may look at the source code. Also, use at least 300 words in your .html to explain Java applet, its components, the control flow of your sample applet and how it works, as if you are a Java tutor teaching a beginner.
4. FAQ:
1). What is inheritance? Design simple programs of your own to explain how the members of superclass are inherited and used in the subclass.
2). What is polymorphism? Design simple programs of your own to explain how Java can call methods polymorphically.
(Note: you may combine #1 and #2 into one program, in other words, design an application of your choice that uses inheritance and polymorphism (i.e. it will process method call polymorphically as shown in JHtP Ch10). It does not have to be very complicated, use sample programs in JHtP Ch9 & 10 for reference. Have a folder named Final to save the screen shots, all .java and .class files for your application. Use best software engineering practices you learned in JHtP Ch9 & 10, for example, declare instance variables as private, have set and methods for instance variables, provide services through public methods, ... and validate data in the setter methods.)
3). What is encapsulation? How to make your programs well-encapsulated?
4). How to prevent the exception of dividing by zero? How to give the user a warning and ask the user to enter a number other than zero? What Java statements can handle that exception so that the program would not terminate?
5). What is object-oriented programming? List and explain at least 2 features of object-oriented programming.
6). What are loop statement(s) for? Give an example that you would use loop statement.
7). What are the benefits from learning programming? (Programming helps you in problem solving, logical thinking, … )
5). (30 Bonus points) How to convert a Java application to an applet. (For this one, you need to compare the Java applications and applets you have worked, and do some research). Give an example, show the application code and applet code. For example, SJP Tutorial 24 Car Payment
can be changed to an applet to offer such service online, as shown in the following screen shot:
Sample screen shot:
Those 4 on the list are links, for example, as the user click on the “Java Programming Language Features, it will link to another .html file, in it you will explain the features and how Java is used in industry. If the user clicks on FAQ, then, it will list all FAQ questions, the use may click on one of them to get the answer.
Hints:
1. Look at the information and demo applets at Sun’s web site:
http://java.sun.com/applets/jdk/1.4/index.html
To see the .html code of the web site, you may click on “View”, then, click on “Source”. Print a copy of the .html code, and compare with the web site display, you can easily figure out the purposes of html tags, for example, you begin with tag, at the end, you end with , to bold a word => you have: the word , to center a line => you have
to have a hyper link => you have whatever you want to show on screen
If you want to have your applet displayed in the center of the screen, have code similar to:
On Sun’s web site (http://java.sun.com/applets/jdk/1.4/index.html), if you click on the “Source Code”, you can see the Java code of the applet.
2. your main page will look similar to the following screen shot, but, on the top, instead of having “JDK 1.4 Demo Applets” you may have “Java Tutor”, and on the left, instead of having “Animator”, “ArcTest”, “BarChart” …links, you will have “Java Programming Language”, “Java Application”, “Java Applet”, “FAQ”, and “How to Convert a Java Application to Applet” (if you choose to do the bonus points one), as show in the above sample screen shot.
3. After the user clicks on the link, say, “Java Animation Applet”, it will show similar to what Sun Microsystems has in their web site, it will run the program, and have a “Source code” link. If the user click on the “Java Programming Language”, it will display a page that explain the features of Java programming language.
4. Be creative, but designing your web pages professionally. You may find a web site that has the format you prefer, again, click on “View” -> “Source”, most of the time, you can get the format html code.
5. If you have your web hosting services, you may upload it online.
6. When you test your html, you may want to use Internet Explorer instead of Firefox, because when you work on applets, sometimes it works in IE but not in Firefox, I know that breaks your heart since you really love Firefox. But, at least you know that’s something you can help to improve after graduation. In some situations, it may work on Firefox, but not Internet Explorer.
7. You may use any tool that you feel most comfortable with, FrontPage, DreamWeaver, …, or even Word. You may use Word to type your answer, then, save it as .html format. In Word, to insert a hyperlink, click on “Insert” -> Hyperlink, then, type in the text to display and the web address.

http://www.jasonjonesprogramming.com/JavaFinalProject/index.htm
Thursday, October 8, 2009
Space ship Design in java applet






/**
* @(#)Plane.java
*
*
* @author
* @version 1.00 2009/10/7
*/
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
public class Plane2 extends JApplet implements KeyListener{
/** Initialization method that will be called after the applet is loaded
* into the browser.
*/
public void init() {
setFocusable(true);
addKeyListener(this);
// TODO start asynchronous download of heavy resources
}
public void paint(Graphics g) {
g.setColor(new Color(89,176,219));
g.fillRect(0,0,600,700);
g.setColor(Color.BLUE);
int[]x={210,200,120,120,220,160,160,220,260,260,250,250,230,210
};
int[]y={190,260,340,380,400,440,460,480,440,400,380,240,200,190
};
g.fillPolygon(x,y,14);
int[]a={350,330,310,310,300,300,340,400,400,340,440,440,360,350
};
int[]b={190,200,240,380,400,440,480,460,440,400,380,340,260,190
};
g.fillPolygon(a,b,14);
g.setColor(new Color(124,5,116));
int[]w={280,260,250,240,230,250,250,260,260,300,300,310,310,330,320,310,300,280
};
int[]z={100,120,140,180,200,240,380,400,440,440,400,380,240,200,180,140,120,100
};
g.fillPolygon(w,z,18);
g.setColor(Color.GREEN);
int[]x1={220,220,230,230,220
};
int[]y1={230,290,300,240,230
};
g.fillPolygon(x1,y1,5);
int[]v1={340,330,330,340,340
};
int[]m1={230,240,300,290,230
};
g.fillPolygon(v1,m1,5);
g.setColor(Color.PINK);
int[]x2={200,160,160,220,220,200
};
int[]y2={300,340,370,380,320,300
};
g.fillPolygon(x2,y2,6);
int[]a2={360,340,340,400,400,360
};
int[]b2={300,320,380,370,340,300
};
g.fillPolygon(a2,b2,6);
///////
g.setColor(new Color(169,49,249));
int[]x3={220,180,220,240,220
};
int[]y3={420,440,460,440,420
};
g.fillPolygon(x3,y3,5);
int[]a3={340,320,340,380,340
};
int[]b3={420,440,460,440,420
};
g.fillPolygon(a3,b3,5);
//////
g.setColor(Color.RED);
int[]x4={270,260,300,290,270
};
int[]y4={130,140,140,130,130
};
g.fillPolygon(x4,y4,5);
g.setColor(new Color(12,5,11));
int[]x5={260,280,300,260
};
int[]y5={180,200,180,180
};
g.fillPolygon(x5,y5,4);
g.setColor(Color.WHITE);
g.fillRect(260,140,40,40);
/////
g.setColor(Color.BLACK);
g.fillRect(270,250,20,10);
g.setColor(Color.GRAY);
g.fillRect(270,260,20,70);
g.setColor(Color.RED);
g.fillRect(270,330,20,10);
g.setColor(Color.BLACK);
int[]x6={270,260,260,270,270,290,290,300,300,290,270
};
int[]y6={340,360,370,360,350,350,360,370,360,340,340
};
g.fillPolygon(x6,y6,11);
g.setColor(Color.ORANGE);
g.fillRect(270,350,20,30);
g.setColor(Color.BLACK);
int[]x7={260,270,290,300,260
};
int[]y7={440,460,460,440,440
};
g.fillPolygon(x7,y7,5);
g.setColor(Color.RED);
int[]x8={270,240,220,250,250,270,280,290,310,310,340,320,290,270
};
int[]y8={460,480,520,500,530,500,520,500,530,500,520,480,460,460
};
g.fillPolygon(x8,y8,14);
}
///////////////////////////////////////
public void keyReleased(KeyEvent kr){
}
public void keyTyped(KeyEvent kt){
}
public void keyPressed(KeyEvent kp){
Graphics g1=getGraphics();
int x=270;
int y=230;
try{
if(kp.getKeyCode()==KeyEvent.VK_J){
// g1.clearRect(0,0,400,400);
g1.fillOval(x,y=y-10,20,20);
Thread.sleep(6);
repaint();
}
}catch(InterruptedException e){
}
///////////////////Action troy
int r=20;
try{
if(kp.getKeyCode()==KeyEvent.VK_A){
g1.clearRect(0,0,600,700);
g1.setColor(new Color(89,176,219));
g1.fillRect(0,0,600,700);
g1.setColor(Color.BLUE);
int[]x9={210-r,200-r,120-r,120-r,220-r,160-r,160-r,220-r,260-r,260-r,250-r,250-r,230-r,210-r
};
int[]y9={190,260,340,380,400,440,460,480,440,400,380,240,200,190
};
g1.fillPolygon(x9,y9,14);
int[]a={350-r,330-r,310-r,310-r,300-r,300-r,340-r,400-r,400-r,340-r,440-r,440-r,360-r,350-r
};
int[]b={190,200,240,380,400,440,480,460,440,400,380,340,260,190
};
g1.fillPolygon(a,b,14);
g1.setColor(new Color(124,5,116));
int[]w={280-r,260-r,250-r,240-r,230-r,250-r,250-r,260-r,260-r,300-r,300-r,310-r,310-r,330-r,320-r,310-r,300-r,280-r
};
int[]z={100,120,140,180,200,240,380,400,440,440,400,380,240,200,180,140,120,100
};
g1.fillPolygon(w,z,18);
g1.setColor(Color.GREEN);
int[]x1={220-r,220-r,230-r,230-r,220-r
};
int[]y1={230,290,300,240,230
};
g1.fillPolygon(x1,y1,5);
int[]v1={340-r,330-r,330-r,340-r,340-r
};
int[]m1={230,240,300,290,230
};
g1.fillPolygon(v1,m1,5);
g1.setColor(Color.PINK);
int[]x2={200-r,160-r,160-r,220-r,220-r,200-r
};
int[]y2={300,340,370,380,320,300
};
g1.fillPolygon(x2,y2,6);
int[]a2={360-r,340-r,340-r,400-r,400-r,360-r
};
int[]b2={300,320,380,370,340,300
};
g1.fillPolygon(a2,b2,6);
///////
g1.setColor(new Color(169,49,249));
int[]x3={220-r,180-r,220-r,240-r,220-r
};
int[]y3={420,440,460,440,420
};
g1.fillPolygon(x3,y3,5);
int[]a3={340-r,320-r,340-r,380-r,340-r
};
int[]b3={420,440,460,440,420
};
g1.fillPolygon(a3,b3,5);
//////
g1.setColor(Color.RED);
int[]x4={270-r,260-r,300-r,290-r,270-r
};
int[]y4={130,140,140,130,130
};
g1.fillPolygon(x4,y4,5);
g1.setColor(new Color(12,5,11));
int[]x5={260-r,280-r,300-r,260-r
};
int[]y5={180,200,180,180
};
g1.fillPolygon(x5,y5,4);
g1.setColor(Color.WHITE);
g1.fillRect(260-r,140,40,40);
/////
g1.setColor(Color.BLACK);
g1.fillRect(270-r,250,20,10);
g1.setColor(Color.GRAY);
g1.fillRect(270-r,260,20,70);
g1.setColor(Color.RED);
g1.fillRect(270-r,330,20,10);
g1.setColor(Color.BLACK);
int[]x6={270-r,260-r,260-r,270-r,270-r,290-r,290-r,300-r,300-r,290-r,270-r
};
int[]y6={340,360,370,360,350,350,360,370,360,340,340
};
g1.fillPolygon(x6,y6,11);
g1.setColor(Color.ORANGE);
g1.fillRect(270-r,350,20,30);
g1.setColor(Color.BLACK);
int[]x7={260-r,270-r,290-r,300-r,260-r
};
int[]y7={440,460,460,440,440
};
g1.fillPolygon(x7,y7,5);
g1.setColor(Color.RED);
int[]x8={270-r,240-r,220-r,250-r,250-r,270-r,280-r,290-r,310-r,310-r,340-r,320-r,290-r,270-r
};
int[]y8={460,480,520,500,530,500,520,500,530,500,520,480,460,460
};
g1.fillPolygon(x8,y8,14);
}
Thread.sleep(20);
}catch(InterruptedException e){
}
}
}
C++ Assignment
1. Write a program that includes the following four steps:
Step 1.Create a structure with the name StudentRecord containing a Name stored as an array of 20 characters, an ID stored as an integer, and a GPA stored as a floating-point number. Create (instantiate) a variable from StudentRecord called TESCStudent.
Step 2. Assign the following values to the variable by assuming Name is SuperProgrammer, with an ID of 1234, and a GPA of 4.0.
Step 3. The program should print out on the screen that SuperProgrammer with an Identification number of 1234 has a 4.0 GPA. (Of course, your program needs to use the structure you defined in step 1.)
Step 4. Generalize the program so that you can input the student's name, ID, and GPA when the program is run. Please do not forget to include prompt statements in your program. Print out the user entered Name, ID, and GPA.
Make sure your program includes all four steps, not just steps 1 and 4.
Section B: Complete either question 1 or 2 in Section B.
1. Define a class called Plot that has private members of length and width. Include a constructor and a public function that calculates the area and the length of the boundary of the field. Use public functions in a program that computes and displays the area and the length of the boundary of the plot where the length and width are 7 and 9 respectively. Hint: The length of the boundary is 2 * (length + width).
2. Recode the Plot class from question 1 above, using inline methods.
Remember that when you submit this assignment, you should acknowledge to your mentor that you have reviewed all programs using a C++ compiler.
When you are ready to submit your assignment, click the View/Complete Assignment link at the bottom of this page, and then use the Browse button to locate and submit your assignment file. Consult the course Calendar for the assignment's due date.
Sunday, October 4, 2009
To analyse a problem in an object-oriented manner, and then design and implement an object- oriented solution that conforms to given specifications
ArrayList and LinkedList in this assignment.
Problem Description
Several organisations across Australia are dedicated to caring for injured wildlife or implementing captive breeding programs for endangered species. The general aims of such organisations are to return healthy animals to their natural environment. Rebecca runs a Recovery and Release Centre that monitors animals that are close to being ready for release and determines when animals in her care will be released. Rebecca has employed you to implement a small interactive information system to manage parts of her Recovery and Release (R&R) Centre.
Rebecca stores all information about each animal in a text file that must be loaded when your program starts. Rebecca’s R and R Program looks after Kangaroos, Joeys, Quolls and Possums. She has paddocks for the Kangaroos and Joeys and the Quolls and Possums are kept in cages.
Information on Kangaroos is stored in 4 lines. A typical entry (record) is:
Kangaroo
M3425
M
1
• Line 1 is the type of animal (Kangaroo, Joey, Possum or Quoll) – not mutable
• Line 2 is a unique electronic tag for the animal – not mutable. All tags begin with M or F (indicating the sex of the animal) followed by 4 digits.
• Line 3 indicates how much longer the animal will stay at the R&R Centre before release.
Possible values are:
S – short-term
M – medium-term
L – long-term
• Line 4 is the paddock number in which the animal has been placed (1 or 2) – not mutable
Information on Joeys (kangaroos not yet adult-sized) is stored in 5 lines. A typical record is:
Joey
F5432
L
2
4.55
• Line 1 is the type of animal – not mutable
• Line 2 is the unique electronic tag for the animal – not mutable
• Line 3 indicates how much longer the animal will stay in the R&R Centre before release
• Line 4 is the paddock number in which the animal has been placed (1 or 2) – not mutable
• Line 5 is the weight of the joey in kg (kangaroos with weights less than or equal to 8kg are classified as joeys by the centre). All joeys are without their mother and are large enough to be cared for in a paddock. Joeys with weights less than 3kg are taken care of at a nearby centre.
Information on Quolls is stored in 5 lines. A typical record is:
Quoll
F1122
S beef|chicken Dav
• Line 1 is the type of animal – not mutable
• Line 2 is the unique electronic tag for the animal – not mutable
• Line 3 indicates how much longer the animal will stay in the R&R Centre before release
• Line 4 is a list of foods that form the quoll’s diet (each food is separated by a ‘|’ character) – not mutable
• Line 5 is the carer of the quoll – not mutable. The carer is responsible for giving the quoll a varied diet from its list of foods. Possible carers are Dav, Josh and Jackie.
Information on Possums is stored in 5 lines. A typical record is:
Possum
M3322
M
apples|bananas|grapes
U7
• Line 1 is the type of animal – not mutable
• Line 2 is the unique electronic tag for the animal – not mutable
• Line 3 indicates how much longer the animal will remain in the R&R Centre before release
• Line 4 is a list of foods that form the possum’s diet – not mutable
• Line 5 indicates the home territory of the possum (the letter U or B for urban or bush, followed by a single digit from 0 to 9) – not mutable. All possums are returned to their home territory.
Task 1 – Animal Hierarchy
Design and implement a class hierarchy to represent the animals at the R&R Centre. As you complete the following tasks which require certain behaviours (methods) of your classes, consider whether any methods or classes should be abstract.
Task 2 – Driver Program which Loads from and Saves to a Text File
Write a menu-based driver program to manipulate the collection of animals at the R&R Centre (and begin coding whatever classes are need for that collection). See the end of this assignment for skeleton code for the menu-based driver program (Driver.java) and an array-based collection of Animal objects (RandRCollection.java) that you may wish to use directly or adapt to your solution.
The program must first ask the user for the name of the text file containing the animal records and load that information into the program. If the file does not exist, a warning message should be displayed to screen before the program continues (with an empty animal collection) by displaying the menu options.
The menu should have the following options (you may display the menu in whatever format you wish and simply output a message for options that are not yet implemented.)
****************** Recovery & Release
****************** S) Show Submenu
A) Add Animal F) Food Lists E) Empty Nest R) R&R
X) BYTE
Q) Quit
****************** Please select:
This menu should repeatedly be displayed after each (case-insensitive) user selection is executed, until the user chooses ‘Q’ or ‘q’ to quit the program.
Before terminating, the collection should be written back to the text file that was used for input (using the same format). If no file was used for input, ask the user for the name of the file in which to save the collection. If the user enters a file name that already exists, repeatedly prompt for a file name until the user enters the name of a file that does not already exist.
Task 3 – Show Submenu
The ShowSubmenu menu option takes the user to a submenu with the following options, repeatedly displayed until the user enters m.
• Options 1) and 2) result in all details of all male Kangaroos and male Joeys in the particular paddock being displayed to screen, followed by a total of those male Kangaroos and male Joeys in the particular paddock. This information helps Rebecca allocate new roos to paddocks.
• Option a) results in all details of all animals displayed to screen.
********************** Show Submenu
**********************
1) Male Roos Paddock 1
2) Male Roos Paddock 2 a) Show All Animals
m) Return to Main Menu
********************** Please select:
Task 4 – Add Animal
The Add Animal menu option prompts the user for the type of animal to add, and then, depending on the animal, prompts for appropriate values for the attributes needed for the animal and adds the animal to Rebecca’s collection.
Task 5 – Food Lists
The Food Lists menu option displays to screen the food needs of all the animals. The information displayed depends on the type of the animal.
• For each Kangaroo, one of the following three lines is output:
Kangaroo: no extra needs
Kangaroo: extra cut grass paddock 1
Kangaroo: extra cut grass paddock 2
If a Kangaroo has a long-term (L) stay value then extra cut grass is placed in that Kangaroo’s paddock (and the output line indicates the paddock number). Otherwise the first line is output.
• For each Joey, one of the following two lines is output:
M1234 Joey: no extra needs
F5643 Joey: milk supplement
If a Joey’s weight is 5kg or less, a milk supplement is given. Otherwise the first line is output.
• For each Quoll, the output starts with the carer’s name followed by the Quoll’s tag and then each food in the Quoll’s food list is written 1 per line, indented 1 space. For example:
Dav F1122 beef chicken
• For each Possum, the output starts with the Possum’s tag and then each food in the Possum’s food list is written 1 per line, indented 1 space. For example:
M3322 apples bananas grapes
Task 6 – Empty Nest
Animals are released (and deleted from Rebecca’s collection) one at a time. When conditions are right, one animal of a particular type with a short-term (S) stay value (if it exists) is released back into its natural environment (and deleted from the collection). Whether an animal was deleted or not, at the same time one animal of the same type with a medium-term (M) stay value (if it exists) has its stay value changed to S and one animal of the same type with a long-term (L) stay value (if it exists) has its stay value changed to M.
For the Empty Nest menu option E) prompt the user for the type of animal to release and if appropriate animals are in the collection, delete one animal of that type (stay value S), and change the stay value from M to S for one animal of that type, and change the stay value from L to M for one animal of that type.
Task 7 – Bunyips and their Billabong Parties
Only a select group of carers is aware of one secret service at Rebecca’s Recovery and Release Centre. On misty nights around the billabongs and other local waterholes, bunyips do gather to party and their dance moves are impressive. When enthusiasm overcomes ability and an injury occurs, Rebecca often receives a call for help!
Information on Bunyips is stored in 4 lines. A typical entry (record) is:
Bunyip
M3425
S
Bill
• Line 1 is the type of animal (Bunyip) – not mutable
Bunyips are too shy to have a picture taken :-(
• Line 2 is a unique electronic tag for the animal – not mutable. All tags begin with M or F (indicating the sex of the animal) followed by 4 digits.
• Line 3 indicates how much longer the animal will stay at the R&R Centre before release.
Possible values are:
S – short-term
M – medium-term
L – long-term
• Line 4 is the name of the Bunyip – not mutable. The Bunyips are shy and the carers call their names at night to coax them out of the billabong at the R&R Centre to take care of them.
Add Bunyips to your Animal hierarchy and make whatever changes are needed to your code to:
• handle Bunyips with other animals in the text files that are initially loaded into the collection and saved when the program ends
• have Bunyip details displayed with other animals at the Show All Animals submenu option
• allow adding a Bunyip at the Add Animal option
• for each Bunyip in the Food Lists option, output the line:
XXXX: no extra needs
Task 8 – Empty Nest (for Bunyips)
When the night is clear and cold, conditions are right to release Bunyips safely. One Bunyip ready for release (stay value S) is written to a binary file called XXXX and deleted from Rebecca’s collection only if the file does NOT already exist.
If a Bunyip is ready for release, check if the file XXXX exists and if it does, print a message to screen and do NOT delete the Bunyip (because we already have a Bunyip in the file waiting for the
Bunyip Team – see Task 9). Whether a Bunyip was deleted or not, at the same time one Bunyip with a medium-term (M) stay value (if it exists) has its stay value changed to S, and one Bunyip with a long-term (L) stay value (if it exists) has its stay value changed to M.
Add code to your Empty Nest menu option to handle Bunyips as required.
Task 9 – BYTE (BunYip TEam to release Bunyips)
Menu option X is used by the BunYip TEam (BYTE) to release one healthy Bunyip. If the file
XXXX does not exist, display an appropriate message to screen.
Otherwise, if the file XXXX exists, read in the Bunyip object and display to screen the tag and name of the Bunyip to call from the billabong for release and then delete the file XXXX.
Task 10 – InvalidAnimalException
Write an InvalidAnimalException class that extends the Exception class. It should have constructors that take a single argument and that take no arguments. Both constructors call the appropriate superclass constructor from the Exception class.
For the Add Animal menu option A), use exception handling to terminate the interactive input of an Animal (and return to the menu) if an incorrect string is entered for the Animal type. Valid values are:
Kangaroo, Joey, Quoll, Possum and Bunyip
------------------------------------------------------------------------------------------------------------------------
Tasks11 –
Robustness
a) Make menu option A) robust by checking that all user input is valid (using exceptions or coding appropriate checks). When an invalid value is input for any attribute value of any Animal, terminate the input of that Animal (and return to the main menu). Valid values for attributes are summarised below.
Characterisitcs Valid Values
type of Animal Kangaroo, Joey, Quoll, Possum or Bunyip
tag M or F followed by 4 digits (each digit is from 0-9 inclusive)
stay or release time S, M or L
paddock 1 or 2
weight of Joey double between 3 and 8 inclusive
food list any strings separated by ‘|’ character
carer Dav, Josh or Jackie
home territory U or B followed by 1 digit (from 0-9 inclusive)
b) Check for incorrect values in the input text file and read over any invalid record.
Rest and Relaxation
c) For menu option R) design a board game that requires traversing a 2-dimensional array
(board) starting in the top left hand corner of the board and proceeding left to right along each row,
until the bottom right-hand corner is reached. Design some elements (squares on the board) that have positive effects on the journey by causing further forward movement and some that cause the player to move backwards. As an initial attempt, you may decide to have just one player and count the number of moves taken to reach the end. You may have a fixed board size and you are free to impose whatever rule restrictions you wish.
Display the board, player(s), and the lucky and unlucky squares to screen, and redisplay the board after each move. On completion of the game, the user is returned to the main menu. (Note Math.random( ) is a useful method for generating random numbers.)
------------------------------------------------------------------------------------------------------------------------
Skeleton Code (to start your answer)
import java.io.*;
public class RandRCollection
{
private Animal[] animals; // i.e. an array of Animal objects
// or whatever name you used
private int numberOfAnimals;
public RandRCollection()
{
animals = new Animal[16];
numberOfAnimals = 0;
}
// see Contacts.java in Lab 6 answers for how this can be useful private void doubleArray()
{
Animal[] newArray = new Animal[animals.length * 2];
for (int i = 0; i < animals.length; ++i)
{
newArray[i] = animals[i];
}
animals = newArray;
}
// and so on ...
}
import java.util.*; import java.io.*; public class Driver
{
private static Scanner keyboard = new Scanner(System.in);
private RandRCollection myAnimals;
public Driver()
{
myAnimals = new RandRCollection();
}
private void runMenu()
{
char input;
do
{
displayMainMenu();
input = keyboard.nextLine().trim().toUpperCase().charAt(0);
switch(input)
{
case 'S':
System.out.println("To be implemented");
break;
case 'A':
System.out.println("To be implemented");
break;
case 'F':
System.out.println("To be implemented");
break;
case 'E':
System.out.println("To be implemented");
break;
case 'R':
System.out.println("To be implemented");
break;
case 'X':
System.out.println("To be implemented");
break;
case 'Q':
System.out.println("Exiting system...");
break;
default:
System.out.println("That was not a valid choice!");
}
} while (input != 'Q');
}
private void displayMainMenu()
{
System.out.println("********************"); System.out.println("Recovery and Release"); System.out.println("********************"); System.out.println("S) Show Submenu"); System.out.println("A) Add Animal"); System.out.println("F) Food Lists"); System.out.println("E) Empty Nest"); System.out.println("R) R&R"); System.out.println("X) BYTE"); System.out.println();
System.out.println("Q) Quit"); System.out.println("********************"); System.out.print("Please select: ");
}
public static void main(String[] args)
{
Driver myDriver = new Driver();
myDriver.runMenu();
}
}
Wednesday, September 23, 2009
Java Simple Program
Extend tax1 activity so that the program can handle a number of items larger than 1. Display pre-tax total, tax amount and total in a form of store receipt. The program still doesn't have to be interactive.
Exercise 2
You need to create a bill of sale for a computer store that sells PCs, printers, monitors, Hard Disks and RAM. Use the following prices :
PC $999.00
Printer $199.00
Monitor $399.00
RAM per Mb $0.20
HD per Gb $1.00
Ask the user how many of each they want to purchase. Assume that sales tax is 7.5%.
Interactive Session Example:
(prompt ‘>’ denotes output provided by your program (to distinguish it from user provided data – it should not be printed by your program) :
>How many PCs do you want to purchase ?
2
>How many printers do you want to purchase ?
3
>How many monitors do you want to purchase ?
2
>How many Mb of RAM do you need ?
64
>How many Gb of hard disk space do you need ?
4
>
> *****************
> * Bill of Sales *
> *****************
>
>Qty. Item Unit price Total price
>-------------------------------------------------------
> 02 PC $999.00 $1998.00
> 03 printer $199.00 $0597.00
> 02 monitor $399.00 $0798.00
> 64 RAM $004.00 $0256.00
> 04 HD $099.00 $0396.00
>-------------------------------------------------------
> Total without tax $4045.00
> Tax $0303.38
> Total with tax $4348.38
Note - the above represents just the form of your output. Numerical values are not necessarily correct.
It is important that your decimal points align.
Exercise 3
Write a program that solves quadratic equation. Given coefficients a, b and c, calculate solutions x1 and x2 according to the following formula:
Your program needs to correctly handle the following cases:
• coefficient a equal to 0
• discriminant equal to 0
• discriminant less than 0
________________________________________
Example 1:
>Enter a:
1
>Enter b:
5
>Enter c:
6
Solutions to equation 1.0*x^2 + 5.0*x + 6.0 = 0 are -2.0 and -3.0
________________________________________
Example 2:
>Enter a:
0
>Enter b:
3
>Enter c:
6
Solution to equation 3.0*x + 6.0 = 0 is -2.0
________________________________________
Example 3:
>Enter a:
1
>Enter b:
2
>Enter c:
3
Solutions to equation 1.0*x^2 + 2.0*x + 3.0 = 0 are not real
________________________________________
Example 4:
>Enter a:
1
>Enter b:
2
>Enter c:
1
Solution to equation 1.0*x^2 + 2.0*x +1.0 = 0 is -1.0
Java Datastructure labs Question
Implement a menu based program with the following array-based list functions:
• ADD (at the end of array)
• INSERT (element at a given location)
• DELETE (element from a given location)
• SHOW (all array elements)
• COUNT (total number of elements)
• CLEAR (initialize array)
Implement a menu based program with the following array-based queue functions:
• ADD (an element to the end of queue)
• DELETE (an element from the front of queue)
• SHOW (all elements, starting at first, ending at last)
• COUNT (total number of elements)
• CLEAR (initialize queue)
Implement a program that will use a stack structure to check for correct placement of parentheses in an algebraic expression. Allow the use of ( ) [ ] { } characters as grouping symbols. Make sure that an error is reported for an expression of a form (...]
Implement a program that will use a stack structure to calculate the value of arithmetic postfix expressions. Assume that only one digit numbers will be used.
Example:
Input 12+3* should generate 9
Monday, September 7, 2009
Java DataStructure Programs
// ArrayIterator.java Authors: Lewis/Chase
//
// Represents an iterator over the elements of an array.
//********************************************************************
package jss2;
import java.util.*;
public class ArrayIterator
{
private int count; // the number of elements in the collection
private int current; // the current position in the iteration
private T[] items;
//-----------------------------------------------------------------
// Sets up this iterator using the specified items.
//-----------------------------------------------------------------
public ArrayIterator (T[] collection, int size)
{
items = collection;
count = size;
current = 0;
}
//-----------------------------------------------------------------
// Returns true if this iterator has at least one more element
// to deliver in the iteraion.
//-----------------------------------------------------------------
public boolean hasNext()
{
return (current < count);
}
//-----------------------------------------------------------------
// Returns the next element in the iteration. If there are no
// more elements in this itertion, a NoSuchElementException is
// thrown.
//-----------------------------------------------------------------
public T next()
{
if (! hasNext())
throw new NoSuchElementException();
current++;
return items[current - 1];
}
//-----------------------------------------------------------------
// The remove operation is not supported in this collection.
//-----------------------------------------------------------------
public void remove() throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
}
------------------------------------------
//********************************************************************
// ArraySet.java Author: Lewis/Chase
//
// Represents an array implementation of a set.
//********************************************************************
package jss2;
import jss2.exceptions.*;
import java.util.*;
public class ArraySet
{
private static Random rand = new Random();
private final int DEFAULT_CAPACITY = 100;
private final int NOT_FOUND = -1;
private int count; // the current number of elements in the set
private T[] contents;
//-----------------------------------------------------------------
// Creates an empty set using the default capacity.
//-----------------------------------------------------------------
public ArraySet()
{
count = 0;
contents = (T[])(new Object[DEFAULT_CAPACITY]);
}
//-----------------------------------------------------------------
// Creates an empty set using the specified capacity.
//-----------------------------------------------------------------
public ArraySet (int initialCapacity)
{
count = 0;
contents = (T[])(new Object[initialCapacity]);
}
//-----------------------------------------------------------------
// Adds the specified element to the set if it's not already
// present. Expands the capacity of the set array if necessary.
//-----------------------------------------------------------------
public void add (T element)
{
if (!(contains(element)))
{
if (size() == contents.length)
expandCapacity();
contents[count] = element;
count++;
}
}
//-----------------------------------------------------------------
// Adds the contents of the parameter to this set.
//-----------------------------------------------------------------
public void addAll (SetADT
{
Iterator
while (scan.hasNext())
add (scan.next());
}
//-----------------------------------------------------------------
// Removes a random element from the set and returns it. Throws
// an EmptySetException if the set is empty.
//-----------------------------------------------------------------
public T removeRandom() throws EmptySetException
{
if (isEmpty())
throw new EmptySetException();
int choice = rand.nextInt(count);
T result = contents[choice];
contents[choice] = contents[count-1]; // fill the gap
contents[count-1] = null;
count--;
return result;
}
//-----------------------------------------------------------------
// Removes the specified element from the set and returns it.
// Throws an EmptySetException if the set is empty and a
// NoSuchElementException if the target is not in the set.
//-----------------------------------------------------------------
public T remove (T target) throws EmptySetException,
NoSuchElementException
{
int search = NOT_FOUND;
if (isEmpty())
throw new EmptySetException();
for (int index=0; index < count && search == NOT_FOUND; index++)
if (contents[index].equals(target))
search = index;
if (search == NOT_FOUND)
throw new NoSuchElementException();
T result = contents[search];
contents[search] = contents[count-1];
contents[count-1] = null;
count--;
return result;
}
//-----------------------------------------------------------------
// Returns a new set that is the union of this set and the
// parameter.
//-----------------------------------------------------------------
public SetADT
{
ArraySet
for (int index = 0; index < count; index++)
both.add (contents[index]);
Iterator
while (scan.hasNext())
both.add (scan.next());
return both;
}
//-----------------------------------------------------------------
// Returns true if this set contains the specified target
// element.
//-----------------------------------------------------------------
public boolean contains (T target)
{
int search = NOT_FOUND;
for (int index=0; index < count && search == NOT_FOUND; index++)
if (contents[index].equals(target))
search = index;
return (search != NOT_FOUND);
}
//-----------------------------------------------------------------
// Returns true if this set contains exactly the same elements
// as the parameter.
//-----------------------------------------------------------------
public boolean equals (SetADT
{
boolean result = false;
ArraySet
ArraySet
T obj;
if (size() == set.size())
{
temp1.addAll(this);
temp2.addAll(set);
Iterator
while (scan.hasNext())
{
obj = scan.next();
if (temp1.contains(obj))
{
temp1.remove(obj);
temp2.remove(obj);
}
}
result = (temp1.isEmpty() && temp2.isEmpty());
}
return result;
}
//-----------------------------------------------------------------
// Returns true if this set is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty()
{
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this set.
//-----------------------------------------------------------------
public int size()
{
return count;
}
//-----------------------------------------------------------------
// Returns an iterator for the elements currently in this set.
//-----------------------------------------------------------------
public Iterator
{
return new ArrayIterator
}
//-----------------------------------------------------------------
// Returns a string representation of this set.
//-----------------------------------------------------------------
public String toString()
{
String result = "";
for (int index=0; index < count; index++)
result = result + contents[index].toString() + "\n";
return result;
}
//-----------------------------------------------------------------
// Creates a new array to store the contents of the set with
// twice the capacity of the old one.
//-----------------------------------------------------------------
private void expandCapacity()
{
T[] larger = (T[])(new Object[contents.length*2]);
for (int index=0; index < contents.length; index++)
larger[index] = contents[index];
contents = larger;
}
}
--------------------------------------------------
//********************************************************************
// ElementNotFoundException.java Authors: Lewis/Chase
//
// Represents the situation in which a target element is not
// present in a collection
//********************************************************************
package jss2.exceptions;
public class ElementNotFoundException extends RuntimeException
{
//-----------------------------------------------------------------
// Sets up this exception with an appropriate message.
//-----------------------------------------------------------------
public ElementNotFoundException (String collection)
{
super ("The target element is not in this " + collection);
}
}
-----------------------------------------------------
//********************************************************************
// EmptySetException.java Authors: Lewis/Chase
//
// Represents the situation in which a set is empty.
//********************************************************************
package jss2.exceptions;
public class EmptySetException extends RuntimeException
{
//-----------------------------------------------------------------
// Creates the exception.
//-----------------------------------------------------------------
public EmptySetException()
{
super ("The set is empty.");
}
//-----------------------------------------------------------------
// Creates the exceptio with the specified message.
//-----------------------------------------------------------------
public EmptySetException (String message)
{
super (message);
}
}
-----------------------------------------------------
package trysets;
import jss2.*;
import java.util.*;
public class IntegerSetTester {
public static void main(String[] args) {
System.out.println("Lab 2: Part I written by YOURNAME");
System.out.println("Creating set1--------------------");
SetADT
}
}
------------------------------------------------
//********************************************************************
// SetADT.java Authors: Lewis/Chase
//
// Defines the interface to a set collection.
//********************************************************************
package jss2;
import java.util.Iterator;
public interface SetADT
{
// Adds one element to this set, ignoring duplicates
public void add (T element);
// Removes and returns a random element from this set
public T removeRandom ();
// Removes and returns the specified element from this set
public T remove (T element);
// Returns the union of this set and the parameter
public SetADT
// Returns true if this set contains the parameter
public boolean contains (T target);
// Returns true if this set and the parameter contain exactly
// the same elements
public boolean equals (SetADT
// Returns true if this set contains no elements
public boolean isEmpty();
// Returns the number of elements in this set
public int size();
// Returns an iterator for the elements in this set
public Iterator
// Returns a string representation of this set
public String toString();
}
--------------------------------------------
package trysets;
import java.io.*;
import java.util.*;
/**
*
Title:
WordReader*
Description:
Provides an "iterator" over the file filename* to return individual words, while removing leading and trailing
* punctuation. WordReader throws an IOException if it is unable
* to open the file corresponding to filename. However, for other
* errors, it reports errors by returning null for the next word.
*/
public class WordReader implements Iterator
private static final String punctuation = ".,:)({}[]';)-=+!@`";
private BufferedReader read;
private String name;
private String nextWord;
private boolean more;
private StringTokenizer tokens;
public WordReader(String filename) throws IOException {
name = filename;
more = true;
read = new BufferedReader(new FileReader(filename));
tokens = null;
updateWord();
}
public boolean hasNext() {
return more;
}
public String next() {
if (!more)
throw new NoSuchElementException("No more words in " + name);
String thisWord = nextWord;
updateWord();
return thisWord;
}
public void remove() {
throw new UnsupportedOperationException(
"Can not remove elements from file");
}
private String trimPunctuation(String word) {
int start = 0;
// find first non-punctuation
int end = word.length();
while (start < end && punctuation.indexOf(word.charAt(start)) != -1) {
start++;
}
if (start >= end) { // all punctuation
return null;
} while (punctuation.indexOf(word.charAt(end - 1)) != -1) {
end--;
}
return word.substring(start, end);
}
private void updateWord() {
try {
while (more) {
if (tokens == null) {
String thisLine = read.readLine();
if (thisLine == null) {
throw new IOException("Empty line");
}
tokens = new StringTokenizer(thisLine);
}
if (tokens.hasMoreTokens()) {
nextWord = trimPunctuation(tokens.nextToken());
if (nextWord != null) {
return;
}
} else {
tokens = null;
}
}
} catch (Exception e) {
more = false;
nextWord = null;
try {
read.close();
} catch (Exception e1) {}
}
}
}
Sunday, September 6, 2009
Sets of Integer and Words
• Become familiar with the SetADT interface
• Learn to use iterators
• Learn to use generic types
• Read files using provided libraries
• Practice incremental development
Hand-in Requirements
• Source for IntegerSetTester.java (10 pts)
• Source for WordSetTester.java (10 pts)
All projects and laboratories will be submitted electronically through webCT. Zip up your entire project directory to submit as the source. (Right click on the project folder and follow the SentTo link.)
Overview:
This project provides practice with using generics, iterators, and the SetADT. You will create two test programs. IntegerSetTester will create sets of integers and perform various set operations on them. WortSetTester will create sets of words from a file and output statistics.
Part I: Sets of integers
• Download the trysetsproject.zip file and import it into your Eclipse workspace as a starting point for this project. Use File -> Import > General -> Existing Projects into Workspace -> Select Archive File to import the zip file, see the "Bringing your program home" section in http://www.cs.utsa.edu/~javalab/lab/eclipse/getstartedeclipse.html for more details on how to import the zipped project.
• Compile and run IntegerSetTester.
• Create a new SetADT called set1 of Integer objects. Use ArraySet as the implementation.
• Add 1000 random Integer objects (with values between 1 and 50) to set1.
• Output set1 and its size. Why doesn't set1 contain 1000 elements?
• Create an Integer iterator for set1. Remove from set1 the first item returned by the iterator.
• Create a second set called set2 by adding 100 random Integer objects with values between 1 and 10.
• Output set2.
• Create a set3 which is the union of set1 and set2. Output set3 and its size.
• (On your own) Create a set4 which is the intersection of set1 and set2. Output set4 and its size.
• (On your own) Find and output the maximum value in set1.
Part II: Reading words from a file using WordReader
The WordReader class provides a String iterator over the words of a file.
• Create a new class called WordSetTester in the trysets project.
• Add code to WordSetTester to create a WordReader for short.txt.
• Write a loop that outputs the successive words obtained from WordReader one per line.
Part III: Creating sets of words from a file
The code in this part should be added to the WordSetTester class of Part III.
• Create a SetADT called shortSet that contains String objects.
• Create a WordReader called shortReader for the file short.txt.
• Add the words in short.txt to shortSet (by iterating through shortReader).
• Output the unique words and the number of unique words in short.txt (by using shortSet).
• (On your own) Create a set called poeSet that contains the words in the file poe.txt. Output the number of unique words in poe.txt.
• (On your own) Output the words that are in both shortSet and poeSet.
• (On your own) Output the words that are in shortSet but not in poeSet.
Simple class hierarchy based on the Currency class
• Become familiar with the rules and facilities.
• Log in to your Windows and Unix accounts.
• Set up your Windows and Unix accounts so that the passwords agree.
• Use a Java development environment
• Create and run a simple Java program using simple classes.
Hand-in Requirements:
• Source code for Currency.java, Quarter.java, Dime.java, Nickel.java and Penny.java (10 pts)
• Source code for CurrencyTester.java (10 pts)
All projects and laboratories have to be Eclipse projects that will be submitted electronically through webCT under the Submissions menu. Zip up your entire project directory to submit as the source. (Right click on the project folder and follow the Send To link.)
Overview:
The goal of this laboratory is for you to get your account set up and to understand how to run simple Java programs. See http://www.cs.utsa.edu/~javalab/lab/accountLogin.html for information on how to set up your account. It is important that you get all account problems resolved in the first week of class. You will have an account on the CS network that works on the Windows, Sun and Linux (Unix) machines in the Computer Science Laboratories. We will mainly be using Windows machines for this course. You will need to log in to both your Windows and Unix accounts to change your passwords if you are new to the system. You can also go to SB 3.02.02 during open laboratory hours ( http://www.cs.utsa.edu/~javalab/lab/schedule.html) and reset your passwords. If you are unfamiliar with the system, please ask a tutor to help. The tutors are available to give you as much help as you need on the laboratories. Please ask for help if you are having trouble.
Part I: Running a simple project
Refer to http://www.cs.utsa.edu/~javalab/lab/eclipse/getstartedeclipse.html for an introduction on how to get started with Eclipse.
When you start Eclipse it will ask you to select a workspace. This is the directory in which all your Eclipse projects will be located. (Theoretically you can switch between different workspaces, but for now let's assume you only have one workspace.) We recommend that you use a directory such as Z:\working\cs2123 as your workspace directory. This laboratory is based on the Currency class. The Currency class has a value, a name, and a two-letter country code. You can find out the name, the value, and the country code. You can also find out whether or not a Currency object is equal to another object. Currency are equal if they are currency with the same name, value, and a country code. (US is the country code for the United States.) All of our classes will also have a toString method for debugging.
Create a new project called currencyproject.
• Open Eclipse and select your workspace directory (such as Z:\working\cs2123\recitations).
• Create a new Eclipse project by selecting File -> New -> Java Project. Give the Name as currencyproject (all lower case). Press Finish.
• Create a Currency class by selecting File -> New -> Class. Use Currency as the Class name and type in currency as the package name. Pay attention to upper and lower case when you type, as Java is case-sensitive. Eclipse will create an empty class called Currency. Implement the functionality of Currency.
• Create a CurrencyTester class which has a main method. (You can select a checkbox that does that for you during the class creation process.)
• Make sure that the main method of CurrencyTester begins with a statement to output the message "This program was written by ... ".
• Add code to CurrencyTester to create a Currency object and to test the methods to get the name and value.
• Create 2 objects of type Currency with different values, but the same names. Output their values using toString. Test to see whether they are equal.
• Also test two different currency objects for equality.
• Create Currency objects with 0 and negative values.
• Create a Quarter class that extends Currency and is specialized to represent quarters. Quarters are US currency. Note: If you have the Currency class (not Currency.java) selected in Eclipse's package explorer and then add a new class, then currency.Currency is automatically selected as the super class. Write test code for Quarter. Subclasses of Currency represent specific denomiations. They should have two constructors: one which is the same as the superclass and one which has no parameters.
Part II: On your own
• Add the following code to CurrencyTester. In a loop which is repeated 10 times, create a new Currency object and assign it to the variable myCurrency. Create each currency object with name theCurrency and value which is a random int value between 1 and 100. Use US as the country code. (Use the Random class with the nextInt method.) Print out each currency object as it is created. After the loop print the maximum currency value, the minimum currency value and the average currency value. Do not use an array.
• Add the Dime, Nickel and Penny classes to the currencyproject. Add test code to CurrencyTester to create and compare various currency.
Monday, August 10, 2009
Hibernate concepts
* Understand the benefits of Hibernate
* Understand the Hibernate architecture
* Create Hibernate based applications
* Understand and use Hibernate mapping to map persistent objects to the database
* Understand and work with collections & associations
o Value and Entity Types
o Bidrectional and unidirectional
o 1-1, 1-N, N-N
* Use Hibernate's versioning support
* Map inheritance hierarchies using Hibernate
* Work with Hibernate queries, HQL, and Criteria
* Performance tune your Hibernate applications
* Understand Hibernate transaction support
* Understand the relationship between Hibernate and Java Persistence / EJB 3
* Use the new Hibernate annotations to do OR mapping
Hibernate Outline
* Introduction to Hibernate
o Issues with Persistence layers and Object-Relational Mapping (ORM)
o Hibernate Overview and Benefits
o Hibernate architecture overview
o POJO (Plain Old Java Object) Based Mapping
* Getting started with Hibernate quickly
o Overview of the Hibernate distribution
o Configuring Hibernate
+ hibernate.cfg.xml file
+ SessionFactory configuration
+ Connection properties, Database dialect
+ Configuration class, Session Interface
o "Hello World" Program for Hibernate
o Mapping a Class
+ Persistent Entity Class, Hibernate Mapping
+ File, Mapping the Entity Class
+ Primary keys: Id property, Generated Id
o Hibernate Type System
o Working with sessions and Persistent Objects
o Logging - log4j Overview and configuration for Hibernate
* Querying
o Inserting and Updating Entities
o HQL - Hibernate Query Language Overview
o The Query Interface
o Creating and working with queries
o Named Queries, Projection Queries, Aggregate Queries
* The Persistence Lifecycle
o Transaction Overview and Transactions in Hibernate
o Hibernate Transaction API (in Managed and Non-managed Environments)
o The lifecycle of managed objects
o Persistent, transient, and detached objects
o The Persistence (Session) Context (Lifespan, Relation to Managed Objects, Propagation)
o Contextual Sessions
o Synchronization to the Database
o The Session as cache
* Optimistic Locking / Versioning
o Detached Objects and Optimistic Locking
o Versioning overview and Using Versioning
o Locking Objects
* Relationships
o Object Relationship Overview
o Mapping Collections of Value Objects
o Entity Relationships: 1-N, N-1, N-N, 1-1
o Mapping Entity Relationships
o Uni and Bi-directional Relationships
o The Relationship "inverse"
o Cascading Over Relationships
o Queries Across Relationships (Lazy and Eager)
* Inheritance Mapping
o Entity Inheritance with Hibernate
o Table-per-class mapping
o Table per Subclass mapping
o Table per Concrete Class mapping
* Additional Querying Capabilities
o Projection Queries, Aggregate queries
o Bulk updates and deletes
o Native SQL Queries
o Query Filters
* The Criteria API
o Overview of the Criteria API
o Working Querying with the Criteria API
o Query by Example
* Hibernate and Java Persistence / EJB 3
o Overview of Java Persistence / EJB 3
o Relationship between Java Persistence and Hibernate
o Overview of Annotations
o Mapping Entities with Hibernate Annotations
o The EntityManager, Persistence Context and Persistence Unit
o Working with Transactions - EntityTransaction, Managed, and Unmanaged Environments
o Inserts and Updates
o JPQL - Java Persistence Query Language
o Versioning
o Relationships
* Advanced Topics
o Components and Multi-Table Mapping
o equals() and hashCode()
o Caching and Efficiency
o Design Considerations
* Conclusion