Mouse Java Applet
In this program will be drawn a rectangle to use an interface. The interface “MouseListener” to allow the user to press the mouse button, drag the mouse and release the mouse button. When I release the mouse button then drawn the rectangle shape with the appropriate upper left corner. The “mousePressed” method will be holds set of coordinates; the user presses the mouse and contain the mouse button initially. The “mouseReleased” will be holds set of coordinates, the user release the mouse button. These coordinates will be holds the upper left and right points of the rectangle. Both methods will be contained the appropriate coordinate's values. The rectangle will be performed by the “paint” method before the rectangle is drawn.
Assumptions
Some mentionable features of the Java which is used in the problem. These are discussed below:
JApplet
Every Java applet is a graphical user interface on which you can place GUI components or draw.
Class Japplet from package javax.swing is used to create applets.
An applet container can create only objects of classes that are public and extend Japplet (or the Applet class from early versions of Java).
An applet container expects every Java applet to have methods named init, start, paint, stop and destroy, each of which is declared in class Japplet. Each new applet class you create inherits default implementations of these methods from class Japplet.
When an applet container loads an applet, the container creates an object of the applet's type, then calls the applet's init, start and paint methods. If you do not declare these methods in your applet, the applet container calls the inherited versions.
The superclass methods init and start have empty bodies, so they do not perform any tasks. The superclass method paint does not draw anything on the applet.
To enable an applet to draw, override its method paint. You do not call method paint explicitly in an applet. Rather, the applet container calls paint to tell the applet when to draw, and the applet container is responsible for passing a Graphics object as an argument.
Java™ How to Program, Sixth Edition, Publishing year- 2004, Author name- H. M. Deitel - Deitel & Associates [30th June 2008]
Here is the JApplet example of the program.
public class Rectangular extends JApplet {
Image offScreenImage;
public void init()
{
setContentPane( new Display() );
offScreenImage = createImage(getSize().width, getSize().height);
Graphics gr = offScreenImage.getGraphics();
gr.setColor(Color.white);
gr.fillRect(0,0,getSize().width,getSize().height);
gr.setColor(Color.black);
gr.drawRect(0,0,getSize().width-1,getSize().height-1);
gr.dispose();
}
//Contain other methods of the class
}
Class
The program unit that houses a method is called a class. A class may contain one or more methods that are designed to perform the class's tasks.
A method can perform a task and return a result.
A class can be used to create an instance of the class called an object. This is one of the reasons Java is known as an object-oriented programming language.
Each message sent to an object is known as a method call and tells a method of the object to perform its task.
Each method can specify parameters that represent additional information the method requires to perform its task correctly. A method call supplies valuescalled argumentsfor the method's parameters.
An object has attributes that are carried with the object as it is used in a program. These attributes are specified as part of the object's class. Attributes are specified in classes by fields.
Each class declaration that begins with keyword public must be stored in a file that has exactly the same name as the class and ends with the .java file-name extension.
Keyword public is an access modifier.
Every class declaration contains keyword class followed immediately by the class's name.
A method declaration that begins with keyword public indicates that the method is "available to the public” that is, it can be called by other classes declared outside the class declaration.
Java™ How to Program, Sixth Edition, Publishing year- 2004, Author name- H. M. Deitel - Deitel & Associates [30th June 2008]
Example of JApplet program of this program.
public class Rectangular extends JApplet
{
//Body of the class
}
Interface
An interface is basically a kind of class. An interfaces contain methods and variables but with a major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Therefore, It is the responsibility of the class that implements an interface to define the code for implementation of these methods.
Programming with JAVA, Second edition, Publishing year- 1998-1999, Author name- E Balagurusamy [30th June 2008]
The general form of an interface definition is:
Interface InterfaceName
{
variables declaration;
methods declaration;
}
An example of an interface definition that contain two variables and one method
Interface Item
{
static final int code=1001;
static final String name =”Fan”;
viod display ();
}
Inner class
An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static member of the outer class and do.
The following program illustrates how to define and use an inner class. The class named Outer has one instance variable named outer_x, one instance method named test (), and defines one inner class called Inner.
The Complete Reference, Seventh Edition, Publishing year- 2007-2008. Author name- Herbert Schildt [1st July 2008]
Class Outer // Start Outer class
{
int outer_x=100;
void test()
{
Inner inner= new Inner();
Inner.display();
}
//Start an inner class
class Inner
{
void display ()
{
System.out.println(“display:outer_x=”+outer_x);
}
} // end Inner class
} // end Outer class
Exception Handling
Java exception handling is managed via five keywords: try, catch, throw, throws and finally. Briefly, here is how they work. Program statements that I want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. My code can catch this exception (using catch) and handle it in some relational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually thrown an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.
This is the general form of an exception-handling block:
The Complete Reference, Seventh Edition, Publishing year- 2007-2008. Author name- Herbert Schildt [1st July 2008]
Try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
finally
{
// block of code to be executed after try block ends
}
Graphics
Java's Graphics class includes methods for drawing many different types of shapes, form simple lines to polygons to text in a variety of fonts. I have already seen how to draw a rectangle using the paint () method and a Graphics object.
To draw a shape on the screen, I may call one of the methods available in the Graphics class. The drawing methods have arguments representing end points, corners, or starting locations of a shape as values in the applet's coordinate system. To draw a shape, I only need to use the appropriate method with the required arguments.
Programming with JAVA, Second edition, Publishing year- 1998-1999, Author name- E Balagurusamy [30th June 2008]
Coordinate system of Java
Different methods of the program
The program in Task-01 has done into many parts using few numbers of methods. These are: void init(), void paintComponent(// Parameter), void drawFigure(// Parameter), void mousePressed(// Parameter), void mouseReleased(// Parameter), void mouseDragged(// Parameter), void mouseClicked(// Parameter).
The uses of these methods are described below:
void init():
The applet's init() method creates a drawing panel to be used as the drawing surface of the applet. It also creates the off-screen image and fills it with a black
rectangle with a white border.
void paintComponent(// Parameter) :
Copy the off-screen image to the screen. If there have not yet been any user actions, show some instructions. If the user is dragging, draw the figure that the user is sketching on top of the permanent picture from the off-screen image.
void drawFigure(// Parameter) :
This is called during dragging to draw the rect between the starting position of the mouse and the current position. The figure is drawn in the graphics context gr. The variables starta, startb, mousea, mouseb.
void mousePressed(// Parameter) :
Respond when the user presses a mouse button.
void mouseReleased(// Parameter) :
End the dragging operation, if one is in progress. Draw the final figure, if any onto the off-screen canvas, so it becomes a permanent part of the image.
void mouseDragged(// Parameter) :
If a dragging operation is in progress, get the new values for mousea and mouseb, and repaint.
void mouseClicked(// Parameter) :
Handle mouse clicked to draw the rectangle.
Program design
Flow Chart:
Fig: Flow chart
Source Code
File name- Rectangular.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Rectangular extends JApplet {
Image offScreenImage;
public void init()
{
setContentPane( new Display() );
offScreenImage = createImage(getSize().width, getSize().height);
Graphics gr = offScreenImage.getGraphics();
gr.setColor(Color.white);
gr.fillRect(0,0,getSize().width,getSize().height);
gr.setColor(Color.black);
gr.drawRect(0,0,getSize().width-1,getSize().height-1);
gr.dispose();
}
class Display extends JPanel implements MouseListener, MouseMotionListener{
boolean heardMouse = false;
boolean dragging;
int starta, startb;
int mousea, mouseb;
Display() {
setBackground(Color.white);
addMouseListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics gr) {
gr.drawImage(offScreenImage,0,0,null);
if (heardMouse == false)
{
}
else if (dragging)
{
drawFigure(gr);
}
}
void drawFigure(Graphics gr) {
if (starta != mousea && starta != mouseb) {
int x, y;
int width;
int hieght;
if (mousea < starta) {
x = starta;
width = starta-mousea;
}
else {
x =starta ;
width = mousea - starta;
}
if (mouseb < startb) {
y = startb;
hieght = startb - mouseb;
}
else {
y = mouseb;
hieght = mouseb - startb;
}
gr.setColor(Color.black);
gr.fillRect(x, y, width, hieght);
gr.drawRect(x, y, width-1, hieght-1);
}
}
public void mousePressed(MouseEvent evt) {
if (heardMouse == false) {
heardMouse = true;
}
if (evt.isShiftDown()) {
Graphics gr = offScreenImage.getGraphics();
gr.setColor(Color.white);
gr.fillRect(0,0,getSize().width,getSize().height);
gr.setColor(Color.black);
gr.drawRect(0,0,getSize().width-1,getSize().height-1);
}
starta = mousea = evt.getX();
startb = mouseb = evt.getY();
dragging = (evt.isMetaDown() == false);
}
public void mouseReleased(MouseEvent evt) {
if (dragging) {
Graphics gr = offScreenImage.getGraphics();
gr.setColor(Color.white);
gr.fillRect(0,0,getSize().width,getSize().height);
gr.setColor(Color.black);
gr.drawRect(0,0,getSize().width-1,getSize().height-1);
drawFigure(gr);
dragging = false;
repaint();
}
}
public void mouseDragged(MouseEvent evt) {
if (dragging) {
mousea = evt.getX();
mouseb = evt.getY();
repaint();
}
}
public void mouseClicked(MouseEvent evt)
{
Graphics gr = offScreenImage.getGraphics();
gr.setColor(Color.white);
gr.fillRect(0,0,getSize().width,getSize().height);
gr.setColor(Color.black);
gr.drawRect(0,0,getSize().width-1,getSize().height-1);
}
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseMoved(MouseEvent evt) { }
}
}
Testing
Step 1: The interface of the program at the beginning.
Figure: Print shot of the first step of the program task-01
Step-2: Press the mouse and to start dragging operation to draw the rectangle.
Figure: Print shot of the second step of the program task-01
Step-3: Release the mouse and end of the dragging operation.
Figure: Print shot of the third step of the program task-01
Step-4: Dragging the mouse, get the new values for mousea and mouseb and repaint
Figure: Print shot of the fourth step of the program task-01
Step-5: Repaint completed
Figure: Print shot of the fifth step of the program task-01
Testing Table
I have no used any types of testing data in this program. Just I have done this program dragging the mouse and draw the rectangle. So I have no need the testing table in this program.
Critical Review of the program
The advantage of the program is that this is operational and functional program.
The strength and weakness of this program is written below:
Strengths
- The output of this program is like the expected figure
- The dragging operation of this program are performing correctly
Weakness
- This program only to draw one rectangle and just one color of the rectangle.
Future Improvement
Will be developed the graphics designed by this program. By this program will be created various types of shape such as- line, oval, parabola, curve etc.
Task-2
Problem definition
In this program will be done these tasks such as- create a text file, array list, unique list, words frequency, create a tree set and search words from the array list. At first will be written a text file which contains number of sentences. To read these file and create an ArrayList then will be composed and convert lowercase all the words of the text file. Only punctuation used are white space, full stop, comma and semicolon. Will be made the UniqueList and TreeSet object to these use will be found out words frequency of all words of the list. A last will be established search words from the ArrayList by input the number of characters and made a temList to sort an alphabetical order.
Assumptions
Some mentionable features of the Java which is used in the problem. These are discussed below:
Class
The program unit that houses a method is called a class. A class may contain one or more methods that are designed to perform the class's tasks.
A method can perform a task and return a result.
A class can be used to create an instance of the class called an object. This is one of the reasons Java is known as an object-oriented programming language.
Each message sent to an object is known as a method call and tells a method of the object to perform its task.
Each method can specify parameters that represent additional information the method requires to perform its task correctly. A method call supplies valuescalled argumentsfor the method's parameters.
An object has attributes that are carried with the object as it is used in a program. These attributes are specified as part of the object's class. Attributes are specified in classes by fields.
Each class declaration that begins with keyword public must be stored in a file that has exactly the same name as the class and ends with the .java file-name extension.
Keyword public is an access modifier.
Every class declaration contains keyword class followed immediately by the class's name.
A method declaration that begins with keyword public indicates that the method is "available to the public” that is, it can be called by other classes declared outside the class declaration.
Java™ How to Program, Sixth Edition, Publishing year- 2004, Author name- H. M. Deitel - Deitel & Associates [30th June 2008]
For example to define a class of this program-
public class ReadFromFile implements Serializable
{
//Body of the class
}
Collection
The Collections Framework was designed to meet several goals. First, the framework had to be high performance. The implementations for the fundamental collections (Dynamic arrays, linked list, trees, and hash tables) are highly efficient. I seldom, If ever, need to code one of these “data engines” manually. Second, the framework had to allow different types of collections to work in similar manner with a high degree of interoperability. Third, extending and/or adapting a collection had to be easy. Towards this end, the entire Collections Framework is built upon a set of standard interfaces. Several standard implementations (such as LinkedList, HashSet and TreeSet) of these interfaces are provided that I may use as-is.
The Complete Reference, Seventh Edition, Publishing year- 2007-2008. Author name- Herbert Schildt [1st July 2008]
File Handling
File handling is an integral part of nearly all programming projects. Files provide the means by which a program stores data, accesses stored data, or shares data. As a result, there are very few applications that don't interact with a file in one form or another. Although no aspect of file handling is particularly difficult, a great many classes, interfaces, and methods are involved. Being able to effectively apply them to my assignment is the mark of a professional.
In Java, file handling is simply a special case aspect of a larger concept because file I/O is tightly integrated into Java's overall I/O system. In general, if understand one part of the I/O system, it's easy to apply that knowledge to another situation. There are two aspects of the I/O system that make this feature possible. The first is that Java's I/O system is build on a cohesive set of class hierarchies, at the top of which are abstract classes that define much of the basic functionality shared by all specific concrete subclasses. The second is the stream. The stream ties together the file system because all I/O operations occur through one.
http://www.geekpedia.com/tutorial 267-file-Handling-in-Java.html [28th June 2008]
Exception Handling
Exception handling is designed to process synchronous errors, which occur when a statement executes. Common examples we will see throughout the book are out-of-range array indices, arithmetic overflow (i.e., a value outside the represent able range of values), and division by zero, invalid method parameters, thread interruption and unsuccessful memory allocation (due to lack of memory). Exception handling is not designed to process problems associated with asynchronous events (e.g., disk I/O completions, network message arrivals, mouse clicks and keystrokes), which occur in parallel with, and independent of, the program's flow of control.
Java™ How to Program, Sixth Edition, Publishing year- 2004, Author name- H. M. Deitel - Deitel & Associates [30th June 2008]
Inheritance
In Java, inheritance is a mechanism that enables one class to inherit both the behavior and the attributes of another class.
The classes I create in object-oriented programming languages can inherit data and methods from existing classes. When I create a class by making it inherit from another class, I am provided with data field and method automatically.
For example, consider the simple Employee class. The class contains two data fields, empNum and empSal and four methods, a get and set method for each field.
public class Employee
{
private int empNum;
private double empSal;
private int getEmpNum()
{
return empNum;
}
public double getEmpSal()
{
return empSal;
}
public void setEmpNum(int num)
{
empNum=num;
}
public void setEmpSal(double sal)
{
empSal=sal;
}
}
IDCS- Java Programming, Second edition, Publishing year- 2004, NCC Education Limited [1st July 2008]
String processing
The String class is defined in the java.lang package and hence is implicitly available to all the programs in Java. The String class is declared as final, which means that it cannot be subclassed. It extends the Object class and implements the Serializable, Comparable, and CharSequence interfaces. Java implements strings as objects of type String. A string is a sequence of characters. Unlike most of the other languages, Java treats a string as a single value rather than as an array of characters. The String objects are immutable, i.e., once an object of the String class is created, the string it contains cannot be changed. In other words, once a String object is created, the characters that comprise the string cannot be changed. Whenever any operation is performed on a String object, a new String object will be created while the original contents of the object will remain unchanged. However, at any time, a variable declared as a String reference can be changed to point to some other String object.
For example-
String Concatenation using the + operator The + operator is used to concatenate two strings, producing a new String object as the result. String sale = "500"; String s = "Our daily sale is" + sale + "dollars"; System.out.println(s);
http://www.geekinterview.com/articles/ [28th June 2008]
Different modules of the program
Some different modules have been used to do this program correctly. These modules include different types of methods and constructor. ReadFromFile(),void getWords(//Parameter), StringTokenizer(),toLowerCase(),void readSentenceFile(),void SearchWord(//Parameter), void makeUniqList(//Parameter), void getFrequency(),void treeSetEntry (//Parameter), void printTreeSet(),WordFrequency(),setWord(//Parameter), void setFrequency(//Parameter), void getFrequency(), void compareTo(//Parameter), void toString().
ReadFromFile(): This constructor to read the sentence from the file of this program.
void getWords(//Parameter): This method to get words from the lines.
StringTokenizer(): This method breaking the lines into the words without delimiter.
toLowerCase(): This method adding words in the arrayList in LowerCase.
void readSentenceFile(): The method read sentences from the sentence.dat file.
void SearchWord(//Parameter): Search the word from the ArrayList into the temporary array list.
void makeUniqList(//Parameter):The method to make a ArrayList inputs unique and save in a new ArrayList.
void getFrequency():The method to get the frequency of each word in the ArrayList.
void treeSetEntry (//Parameter): This method takes a WordFrequency object and inputs it in the "wordSet".
void printTreeSet():The method to print the elements of the treeSet.
WordFrequency(): This constructor find the frequency of the words.
setWord(//Parameter): This method set the words to the unique list.
void setFrequency(//Parameter): The method set frequency words of the unique list.
void getFrequency(): Get frequency of the words using this method.
void compareTo(//Parameter): A comparable interface implementation must include overridden definition of compareTo method
void toString():Override toString method to show the elements of the WordFrequency object
Program design
Flowchart:
Fig: Flow chart task-2
Source code
File name: ReadFromFile.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.*;
import java.lang.String;
public class ReadFromFile implements Serializable
{
public static ArrayList words=new ArrayList();//creating arraylist of words
public static ArrayList uniqList=new ArrayList();//creating list of unique words
UniqueArraylist ua=new UniqueArraylist();
public ReadFromFile()
{
readSentenceFile();//calling method to read the sentence file
ua.makeUniqList(words);//calling method of UniqueArraList class to make uniqueList
ua.getFrequency();//calling method of UniqueArraList class to get frequency
}
private void getWords(String str)
{
StringTokenizer st=new StringTokenizer(str," .,;");
while (st.hasMoreElements())
{
String val=st.nextToken();//breaking the lines into words
words.add(val.toLowerCase());//adding words in the arrayList in LowerCase
System.out.println(val);
}
}
private void readSentenceFile()
{
BufferedReader in= null;
try
{
in=new BufferedReader(new FileReader("Sentences.dat"));
String l="";
while((l=in.readLine())!=null)
{
getWords(l); //calling method to get the words from the lines
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
if(in != null)
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println();
System.out.println("From ArrayList: \n");
System.out.println("Words in arrayList: "+words);//printing the arrayList after adding
//all the words
}
public void SearchWord(int in)
{
ArrayList tmpList= new ArrayList(); //temporary ArrayList
for(int i=0;i<words.size();i++)
{
String s = words.get(i).toString();
int wordLen= s.length();
if(wordLen==in)
{
tmpList.add(s);
}
}
Collections.sort(tmpList);
System.out.print("Words matched: ");
System.out.println(tmpList);
}
}
File name: sentences.dat
There is a mad rush to the supermarket this morning.
The traffic was so bad this morning it took us thirty minutes longer to reach the supermarket.
File name:UniqueArraylist.java
import java.util.ArrayList;
import java.io.Serializable;
public class UniqueArraylist implements Serializable
{
public static ArrayList uniqList=new ArrayList();
//method to make a ArrayList inputs unique and save in a new ArrayList
public void makeUniqList(ArrayList al)
{
for(int i=0;i<al.size();i++)
{
if(!uniqList.contains(al.get(i)))
{
uniqList.add(al.get(i));
}
}
System.out.println();
System.out.println("Unique ArrayList is: "+uniqList);
}
//method to get the frequency of each word in the ArrayList
public void getFrequency()
{
int countFreq;
for(int i=0;i<uniqList.size();i++)
{
countFreq=0;
for(int j=0;j<ReadFromFile.words.size();j++)
{
//comparing each words from "words" ArrayList to
//words in "uniqList" ArrayList
if(uniqList.get(i).equals(ReadFromFile.words.get(j)))
{
countFreq=countFreq+1;
}
}
WordFrequency wf=new WordFrequency();//object of class WordFrequency
wf.setWord(uniqList.get(i).toString());
wf.setFrequency(countFreq);
UseTreeSet.treeSetEntry(wf);//sending object to add in the treeSet
}
UseTreeSet.printTreeSet();
}
}
File name:WordFrequency.java
public class WordFrequency implements Comparable
{
String word;
int frequency;
public WordFrequency()
{
}
public WordFrequency(String s,int i)
{
word=s;
frequency= i;
}
public void setWord(String s)
{
word=s;
}
public String getWord()
{
return word;
}
public void setFrequency(int f)
{
frequency=f;
}
public int getFrequency()
{
return frequency;
}
//a comparable interface implementation must
//include overriden defination of compareTo method
public int compareTo(Object o1)
{
if (this.word.equals(((WordFrequency) o1).word)&&this.frequency ==(((WordFrequency) o1).frequency))
return 0;
else
return 1;
}
//override toString method to show the elements of the WordFrequency object
public String toString()
{
return word+" ----->"+frequency+"\n";
}
}
File name:UseTreeSet.java
import java.util.TreeSet;
import java.util.Iterator;
import java.util.ArrayList;
public class UseTreeSet
{
public static TreeSet wordSet=new TreeSet();
//this method takes a WordFrequency object and inputs it in the "wordSet"
public static void treeSetEntry (WordFrequency wrd)
{
String s= wrd.getWord();
int i=wrd.getFrequency();
wordSet.add(new WordFrequency(s,i));
}
//method to print the elements of the treeSet
public static void printTreeSet()
{
Iterator it=wordSet.iterator();
System.out.println();
System.out.println("From TreeSet: \n");
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
File name: Main.java
import java.util.TreeSet;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
ReadFromFile reader=new ReadFromFile(); //to read from file
System.out.println("Do you want to Search any word");
System.out.println("Please enter the number of Characters of the Word");
Scanner s = new Scanner(System.in) ;
int input = s.nextInt();
reader.SearchWord(input);//calling method to search words
}
}
Testing
Step-1: To show the tokenize words and these words in array list and to show unique array list and these words to show the frequency.
Fig: Print sort of the first step of this program.
Step-2: Input the number of character of the words
Fig: Print sort of the second step of this program.
Step-3: To show the matched words from the ArrayList list.
Fig: Print sort of the third step of this program.
Testing Table
ArrayList: There is a mad rush to the supermarket this morning.
The traffic was so bad this morning it took us thirty minutes longer to reach the supermarket.
i<al.size() |
(!uniqList.contains(al.get(i)) |
uniqList.add(al.get(i)) |
for loop |
Display uniqList |
|
There, is, a mad, rush, to, the, supermarket, this, morning, Traffic, was, so, bad, it, took, us, thirty, minutes, longer, reach |
UniqueList : There, is, a mad, rush, to, the, supermarket, this, morning, Traffic, was, so, bad, it, took, us, thirty, minutes, longer, reach
i<uniqList.size() |
j<ReadFromFile.words.size() |
(uniqList.get(i).equals(ReadFromFile.words.get(j)) |
for loop |
Display WordsFrequency |
|
There…1,is….1, a…1,mad…1,rush…1,to…2,the..3,supermarket..2,this..2,morning..2,Traffic..1, was..1, so…1, bad..1,it..1,took…1,us..1,thirty…1,minutes…1, longer…1, reach..1 |
ArrayList: There is a mad rush to the supermarket this morning.
The traffic was so bad this morning it took us thirty minutes longer to reach the supermarket.
wordLen= 1,2,3,4,5,6,7,8,9,10,11
Input number of characters |
CompareTo() |
add() |
Sort() |
Expected output |
Actual output |
1 |
wordLen= =1 |
Words matched [a] |
Words matched [a] |
Words matched [a] |
Words matched [a] |
2 |
wordLen= =2 |
Words matched [is, to, so, it, us, to] |
Words matched [is, it, so, to, to, us] |
Words matched [is, it, so, to, to, us] |
Words matched [is, it, so, to, to, us] |
3 |
wordLen= =3 |
Words matched [mad, the, the, was, bad, the] |
Words matched [bad, mad, the, the, the, was] |
Words matched [bad, mad, the, the, the, was] |
Words matched [bad, mad, the, the, the, was] |
4 |
wordLen= =4 |
Words matched [rush, this, this, took ] |
Words matched [rush, this, this, took] |
Words matched [rush, this, this, took ] |
Words matched [rush, this, this, took] |
5 |
wordLen= =5 |
Words matched [there, reach] |
Words matched [reach, there] |
Words matched [reach, there] |
Words matched [reach, there] |
6 |
wordLen= =6 |
Words matched [thirty, longer,] |
Words matched [longer, thirty] |
Words matched [longer, thirty] |
Words matched [longer, thirty] |
7 |
wordLen= =7 |
Words matched [morning, traffic, morning, minutes] |
Words matched [minutes, morning, morning, traffic] |
Words matched [minutes, morning, morning, traffic] |
Words matched [minutes, morning, morning, traffic] |
8 |
wordLen= =8 |
Words matched [] |
Words matched [] |
Words matched [] |
Words matched [] |
9 |
wordLen= =9 |
Words matched [] |
Words matched [] |
Words matched [] |
Words matched [] |
10 |
wordLen= =10 |
Words matched [] |
Words matched [] |
Words matched [] |
Words matched [] |
11 |
wordLen= =11 |
Words matched [supermarket, supermarket] |
Words matched [supermarket, supermarket] |
Words matched [supermarket, supermarket] |
Words matched [supermarket, supermarket] |
Critical Review of the program
The critical review of this program is discussed below:
Strengths
- This program can calculate correctly
- All methods are working properly
- Output is valid
Weakness
- There is no graphical user interface
Future Improvement
- Graphical user interface will be needed further improvement
Task-3
Problem definition
This program about a restaurant serves the customers. A restaurant has a Shelf where the two Cooks and four Waitresses coordinate their tasks. The Shelf has a capacity for four trays. The cooks complete an order, place it on a tray and place the tray on the shelf. The waitresses take the tray from the shelf and serve the customers. When the shelf is full, the cooks can not put another tray on the shelf and the shelf is empty then the waitresses has to wait for the order and serves the customers. This program will be run two threads use of the four slot shelf will be shared between cooks and waitresses.
Assumptions
Some mentionable features of the Java which is used in the problem. These are discussed below:
Class
Technically, in this program I have created is a thread. I have also created a thread by extending the Thread class, which is defined in the java.lang package. The Thread class contains a method named run (). I override the run () method in my extended class to tell the system how to execute the Thread. For example, I can write the HelloThread class which prints a “Hello” message to the screen 100 times. Here the HelloThread class contain a single method.
Class HelloThread extends Thread
{
public void run ()
{
for (int x=0; x<100; x++)
System.out.print(“Hello”);
}
}
IDCS- Java Programming, Second edition, Publishing year- 2004, NCC Education Limited [1st July 2008]
Thread
Tread is a single line of execution within a program. Multiple threads can run concurrently in a single program. Creating threads in java is simple. Threads are implemented in the form of objects that contain a method called run (). The run () method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the thread's behavior can be implemented. Within a program thread can be implemented single or multiple. Both of examples are given below:
Class ABC
{
……………….
……………….
……………….
…………….....
………………..
………………..
}
Beginning
Single-threaded body of execution
End
Fig-1: Single-threaded program
Fig-2: Multiple threaded program
Programming with JAVA, Second edition, Publishing year- 1998-1999, Author name- E Balagurusamy [30th June 2008]
Synchronized methods
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. To enter an object's monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method.
Java™ How to Program, Sixth Edition, Publishing year- 2004, Author name- H. M. Deitel - Deitel & Associates [30th June 2008]
Exception Handling
Exception handling is designed to process synchronous errors, which occur when a statement executes. Common examples we will see throughout the book are out-of-range array indices, arithmetic overflow (i.e., a value outside the representable range of values), and division by zero, invalid method parameters, thread interruption and unsuccessful memory allocation (due to lack of memory). Exception handling is not designed to process problems associated with asynchronous events (e.g., disk I/O completions, network message arrivals, mouse clicks and keystrokes), which occur in parallel with, and independent of, the program's flow of control. Example of Exception handling of this program
Java™ How to Program, Sixth Edition, Publishing year- 2004, Author name- H. M. Deitel - Deitel & Associates [30th June 2008]
try
{
Thread.sleep(genRandom.nextInt(3000));
sharedLocation.setTray(count);
//System.out.printf("\t%2d\n",count);
}
catch(InterruptedException exception)
{
exception.printStackTrace();
}
Different module of this program
I have used different methods and constructors of this program these are- Cook(//Parameter), void setTray(//Parameter), void getTray(),Waitresses(//Parameter),canKeep.await(),canRemove.await(), canRemove.signal(),canKeep.signal(),void run(). These methods and constructors are briefly described below:
Cook(//Parameter): This constructor create sharedLocation of type Shelf.
Waitresses(//Parameter): This constructor create sharedLocation of type Shelf.
void setTray(//Parameter):Place the int value into the Shelf.
void getTray(): Return the int value from the Shelf.
canKeep.await(): In this method the Cook wait until Shelf is empty.
canRemove.await():In this method the Waitresses wait until Shelf is full.
canRemove.signal(): Give the remove signal from the Shelf in this method.
canKeep.signal(): Give the keep signal into the Shelf.
void run(): Store value from 1 to 5 in sharedLocation
Program design
Flow chart:
Fig: Flow chart of the task-3
Source Code
File name:Shelf.java
public interface Shelf
{
public void setTray(int value);
public void getTray();
}
File name: Cook.java
import java.util.Random;
public class Cook implements Runnable
{
private static Random genRandom=new Random();
private Shelf sharedLocation;
public Cook(Shelf shared)
{
sharedLocation=shared;
}
public void run()
{
for(int count=1;count<=5;count++)
{
try
{
Thread.sleep(genRandom.nextInt(3000));
sharedLocation.setTray(count);
}
catch(InterruptedException exception)
{
exception.printStackTrace();
}
}
System.out.println("\nCook keeping tray .....Terminating cook");
}
}
File name: Waittresses.java
import java.util.Random;
public class Waitresses implements Runnable
{
private static Random genRandom=new Random();
private Shelf sharedLocation;
public Waitresses(Shelf shared)
{
sharedLocation=shared;
}
public void run()
{
for(int count=1;count<=5;count++)
{
try
{
Thread.sleep(genRandom.nextInt(3000));
sharedLocation.getTray();
}catch(InterruptedException exception)
{
exception.printStackTrace();
}
}
//System.out.println("Waitress remove values "+ sharedLocation.getTray()+".....Terminating Waitress");
}
}
File name: SynchronizedShelf.java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
public class SynchronizedShelf implements Shelf
{
private Lock accessLock=new ReentrantLock();
private Condition canKeep=accessLock.newCondition();
private Condition canRemove=accessLock.newCondition();
private int shelf=0;
private boolean full=false;
private boolean empty=true;
public void setTray(int value)
{
accessLock.lock();
try
{
if(full)
{
System.out.println("Cook tries to keep ");
displayState("Shelf full.Cook waits...");
canKeep.await();
}
if(shelf>=0&&shelf<=4)
{
shelf+=1;;
empty=false;
if(shelf==4)
{
full=true;
}
}
else
{
full=true;
}
displayState("Cook keep tray " );
canRemove.signal();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
accessLock.unlock();
}
}
public void getTray()
{
accessLock.lock();
try
{
if(empty)
{
System.out.println("Waitress tries to remove tryes ");
displayState("shelf is empty.waitress waits...");
canRemove.await();
}
if(shelf>0&&shelf<=4)
{
shelf-=1;
if(shelf==0)
{
empty=true;
}
}
else
{
empty=true;
}
displayState("Waitresses remove tray..");
canKeep.signal();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
accessLock.unlock();
}
}
public void displayState(String operation)
{
System.out.printf("%-40s%s\t\t\n\n\n",operation,shelf);
}
}
File name: SyncSharedShelfTest.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SyncSharedShelfTest
{
public static void main(String args[])
{
ExecutorService application=Executors.newFixedThreadPool(2);
Shelf sharedLocation=new SynchronizedShelf();
System.out.printf("%-40s%s\t\t\n\n\n","Operation", "shelf","",".....",".....\t\t.....");
try
{
application.execute(new Cook(sharedLocation));
application.execute(new Waitresses(sharedLocation));
}
catch(Exception e)
{
}
finally
{
application.shutdown();
}
}
}
Testing
Output of the program:
Fig: Print sort of the program in task-3
Testing Table
Shelf!=empty |
Shelf=empty |
Operation |
Shelf |
False |
True |
Cook keep tray |
1 |
True |
True |
Waitresses remove tray |
0 |
False |
True |
Waitresses wait |
0 |
True |
False |
Cook keep tray |
1 |
True |
True |
Waitresses remove tray |
0 |
True |
False |
Cook keep tray |
1 |
True |
True |
Waitresses remove tray |
0 |
False |
True |
Waitresses wait |
0 |
True |
False |
Cook keep tray |
1 |
True |
True |
Waitresses remove tray |
0 |
True |
False |
Cook keeping tray…terminating Cook |
|
True |
True |
Waitresses remove tray |
0 |
Critical Review of the program
The critical review of the program is discussed below:
Strengths
- The program can update data.
- Thread class is functional
- Synchronization is functional
- Output is received correctly
Weakness
- Not more than two Cooks and four Waitresses can use the program simultaneously.
Future Improvement
This program will be improved, where more than two cooks and four waitresses will be used the program simultaneously
Bibliography
[1] Java™ How to Program, Sixth Edition, Publishing year- 2004, Author name- H. M. Deitel - Deitel & Associates [30th June 2008]
[2] Programming with JAVA, Second edition, Publishing year- 1998-1999, Author name- E Balagurusamy [30th June 2008]
[3] IDCS- Java Programming, Second edition, Publishing year- 2004, NCC Education Limited [1st July 2008]
[4] The Complete Reference, Seventh Edition, Publishing year- 2007-2008. Author name- Herbert Schildt [1st July 2008]
[5] http://www.geekpedia.com/tutorial 267-file-Handling-in-Java.html [28th June 2008]
[6] http://www.geekinterview.com/articles/ [28th June 2008]
We provide a professional essay writing service that thousands of our customers use as an effective way of improving their grades, improving their research and saving them lots of time.

