Sunday, January 17, 2010

Parsing String using JAVA

Write a java program that takes as input (on System.in) a sequence of lines of text (consisting of left-/right-parentheses, alphanumeric characters and spaces) and then produces as output a sequence of the “token” “(words) one-per-line in the order they exist in the input. Each token should consist of either a single left- or right-parenthesis, a sequence of. You may wish to make use of the methods in the java.util.Scanner and java.lang.String.

Wednesday, October 21, 2009

Binary Search tree using in Java

public class BinarySearchTree_temp {
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

Assignment #5
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

Design Java Tutor web pages that will have at least the followings. (Look at page 3 for a sample screen shot).

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

the line
,
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

Section A: Complete question 1 in Section A. 
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

PLEASE NOTE: You are NOT permitted to use container classes from the API such as
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();
}
}