Post on 04-Apr-2018
transcript
7/30/2019 Stack Using Linklist
1/70
3 STACK USING LINKED LIST 21.7.2010
AIM:
To implement stack using linked list.
ALGORITHM:
Step 1:Start the program.
Step 2:Initialize head and tail as null.
Step 3:Define a method to insert into the head of the stack.
Step 4:Define a method to retrieve top element of the stack.
Step 6:Based on user input do necessary operation.
Step 7:Close the program.
7/30/2019 Stack Using Linklist
2/70
STACK USING LINKLIST
PROGRAM:
import java.util.Scanner;class Link
{public Object data;
public Link next;public Link(Object d, Link n)
{
data = d; next = n;}
}
//LINKEDLIST CLASS AND MAINclass LinkList
{
private Link head; // reference to first Linkprivate Link tail; // reference to last Linkprivate int size;
public LinkList()
{tail = null;
head = null;
}public Object peekHead() // return reference to first Object
{
return head.data;
}public Object peekTail() // return reference to last Object
{
return tail.data;}
//THE ADD METHOD, NOT SURE IF DONE RIGHT
public void addHead(Object newData){
if (head == null)
{head = new Link(newData, tail);
}
else if (head != null && tail == null)
{tail = head;
head = new Link (newData, tail);
}else
{
7/30/2019 Stack Using Linklist
3/70
head.next = head;
head = new Link (newData, head.next);}
}
public void addTail(Object newData){
}
//THE REMOVE METHODpublic Object removeHead()
{
Link removing = head;
if (head != null){
head = head.next;
}return removing.data;
}
//MAIN METHOD
public static void main (String[] args){
Scanner scan = new Scanner(System.in);int choice = 0;
LinkList first = new LinkList();
while (choice != 6)
{System.out.println("What would you like to do? (enter the number)");
System.out.println("1 - Push onto Head of Stack.");
System.out.println("2 - Remove from Head of Stack.");System.out.println("3 - Peek at Head of Stack.");
System.out.println("4 - Push at Tail of Stack.");System.out.println("5 - Peak at Tail of Stack.");System.out.println("6 - Close Program.");
choice = scan.nextInt();
switch(choice)
{case 1:
System.out.println("What do you want to push on Head?");
Object pushingHead = scan.next();first.addHead(pushingHead);
break;
case 2:System.out.println("Removing: " + first.removeHead());
break;
case 3:System.out.println("Peeking at Head of Stack: " + first.peekHead());
break;
case 4:
7/30/2019 Stack Using Linklist
4/70
System.out.println("What do you want to push on Tail?");
Object pushingTail = scan.next();first.addHead(pushingTail);
break;
case 5:System.out.println("Peeking at Tail of Stack: " + first.peekTail());
break;
case 6:System.out.println("Good Bye!");
break;
}
}}
}
OUTPUT:
C:\Program Files\Java\jdk1.6.0_17\bin>javac LinkList.javaC:\Program Files\Java\jdk1.6.0_17\bin>java LinkList
What would you like to do? (enter the number)1 - Push onto Head of Stack.
2 - Remove from Head of Stack.
3 - Peek at Head of Stack.4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.
6 - Close Program.
1
What do you want to push on Head?25
What would you like to do? (enter the number)1 - Push onto Head of Stack.
2 - Remove from Head of Stack.
3 - Peek at Head of Stack.
4 - Push at Tail of Stack.5 - Peak at Tail of Stack.
6 - Close Program.
1
What do you want to push on Head?35
What would you like to do? (enter the number)1 - Push onto Head of Stack.
7/30/2019 Stack Using Linklist
5/70
2 - Remove from Head of Stack.
3 - Peek at Head of Stack.4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.
6 - Close Program.
3
Peeking at Head of Stack: 35
What would you like to do? (enter the number)
1 - Push onto Head of Stack.
2 - Remove from Head of Stack.3 - Peek at Head of Stack.
4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.6 - Close Program.
2
Removing: 35
What would you like to do? (enter the number)1 - Push onto Head of Stack.
2 - Remove from Head of Stack.
3 - Peek at Head of Stack.
4 - Push at Tail of Stack.5 - Peak at Tail of Stack.
6 - Close Program.
4
What do you want to push on Tail?89
What would you like to do? (enter the number)
1 - Push onto Head of Stack.
2 - Remove from Head of Stack.3 - Peek at Head of Stack.
4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.6 - Close Program.
4What do you want to push on Tail?
59
7/30/2019 Stack Using Linklist
6/70
What would you like to do? (enter the number)
1 - Push onto Head of Stack.2 - Remove from Head of Stack.
3 - Peek at Head of Stack.
4 - Push at Tail of Stack.5 - Peak at Tail of Stack.
6 - Close Program.
5
Peeking at Tail of Stack: 25
What would you like to do? (enter the number)1 - Push onto Head of Stack.
2 - Remove from Head of Stack.
3 - Peek at Head of Stack.4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.
6 - Close Program.
6
Good Bye!
RESULT:
Thus the program is written to implement stack using linked list.
7/30/2019 Stack Using Linklist
7/70
6 READ FILE CONTENT 11.8.2010
AIM:
To develop a java program that reads file content and prints no of chars, lines, words, vowels.
ALGORITHM:
Step 1: Declare the class DateCalender
Step 2:Inside class declare void main
Step 3: Declare integer variables
Step 4:using getchar get size ,length,buffer,starting location
Step 5:using for loop get check for vowels
Step 6:using object f1 write char to buffer
Step 7:read the content written
Step 8: stop the program
7/30/2019 Stack Using Linklist
8/70
PRINT NO OF CHARS, LINES, WORDS, AND VOWELS.
PROGRAM:
import java.io.*;
class DateCalendar
{
public static void main(String args[])throws Exception
{
int i,l=0,w=0,vow=0;
String s="it is java program"+"\nplatform independent";
char buffer[]=new char[s.length()];
s.getChars(0,s.length(),buffer,0);
System.out.println("no of characters="+s.length());
for(i=0;i
7/30/2019 Stack Using Linklist
9/70
OUTPUT:
C:\Program Files\Java\jdk1.6.0_17\bin>javac DateCalendarr.java
C:\Program Files\Java\jdk1.6.0_17\bin>java DateCalendarr
no of characters=39
no of words:5
no of vowels:12
no of lines2
RESULT:
Thus the program is written to print number of characters, vowels in a file.
7/30/2019 Stack Using Linklist
10/70
7 PRINTING CURRENT DATE AND TIME 11.8.2010
AIM:
To write a java program to print current date and time.
ALGORITHM:
Step 1:Start the program.
Step 2:Create an object for date foramt class.
Step 3:From the string of months get the instance.
Step 3:Print the current date,time.
Step 4:Stop.
7/30/2019 Stack Using Linklist
11/70
DATE & TIME
PROGRAM:
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
class DateCalendar {
public static void main(String args[]) {
System.out.println("Display current date and time using Date class>>> ");Date d = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
String formattedDate = formatter.format(d);System.out.println("Today's date and Time is:"+d);
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug","Sep", "Oct", "Nov", "Dec"};
Calendar calendar = Calendar.getInstance();System.out.println("Display current date and time using Calendar class>>>> ");
System.out.print("Date: ");
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");System.out.println(calendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
}
}
OUTPUT:C:\Program Files\Java\jdk1.6.0_17\bin>javac DateCalendar.java
C:\Program Files\Java\jdk1.6.0_17\bin>java DateCalendar
Display current date and time using Date class>>>Today's date and Time is:Sun Sep 26 08:38:11 IST 2010
Display current date and time using Calendar class>>>>
Date: Sep 26 2010Time: 8:38:11
RESULT:
Thus the program is written to print current date and time.
7/30/2019 Stack Using Linklist
12/70
15 MULTI-THREADED GUI 23.9.2010
AIM:
To develop a multithreaded GUI application.
ALGORITHM:
1.Import the required packages.
2.Create class that implements actionlistener and mouse listener.
3.Create menus,menuitems,buttons.
4.Add menuitems to menus and buttons to toolbars.
5.Add mouse listener and perform necessary operation.
6.Exit the application.
7/30/2019 Stack Using Linklist
13/70
GUI APPLICATION
PROGRAM:
ChatServer.java
import java.io.*;
import java.util.*;
import java.net.*;
import static java.lang.System.out;
public class ChatServer {
Vector users = new Vector();Vector clients = new Vector();
public void process() throws Exception {
ServerSocket server = new ServerSocket(9999,10);
out.println("Server Started...");while( true) {
Socket client = server.accept();
HandleClient c = new HandleClient(client);
clients.add(c);
} // end of while
}
public static void main(String ... args) throws Exception {
new ChatServer().process();
} // end of main
public void boradcast(String user, String message) {
// send message to all connected usersfor ( HandleClient c : clients )
if ( ! c.getUserName().equals(user) )
c.sendMessage(user,message);
}
class HandleClient extends Thread {
String name = "";
BufferedReader input;
PrintWriter output;
public HandleClient(Socket client) throws Exception {
// get input and output streamsinput = new BufferedReader( new InputStreamReader( client.getInputStream())) ;
output = new PrintWriter ( client.getOutputStream(),true);
// read name
name = input.readLine();
users.add(name); // add to vector
start();
}
public void sendMessage(String uname,String msg) {
7/30/2019 Stack Using Linklist
14/70
output.println( uname + ":" + msg);
}
public String getUserName() {
return name;
}
public void run() {
String line;try {
while(true) {
line = input.readLine();if ( line.equals("end") ) {
clients.remove(this);
users.remove(name);
break;
}
boradcast(name,line); // method of outer class - send messages to all
} // end of while
} // try
catch(Exception ex) {System.out.println(ex.getMessage());
}
} // end of run()
} // end of inner class
} // end of Server
ChatClient.java
import java.io.*;import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;import java.awt.event.*;
import static java.lang.System.out;
public class ChatClient extends JFrame implements ActionListener {
String uname;
PrintWriter pw;
BufferedReader br;
JTextArea taMessages;
JTextField tfInput;
JButton btnSend,btnExit;
Socket client;
public ChatClient(String uname,String servername) throws Exception {
super(uname); // set title for frame
this.uname = uname;
client = new Socket(servername,9999);
br = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
7/30/2019 Stack Using Linklist
15/70
pw = new PrintWriter(client.getOutputStream(),true);
pw.println(uname); // send name to server
buildInterface();
new MessagesThread().start(); // create thread for listening for messages
}
public void buildInterface() {
btnSend = new JButton("Send");btnExit = new JButton("Exit");
taMessages = new JTextArea();
taMessages.setRows(10);taMessages.setColumns(50);
taMessages.setEditable(false);
tfInput = new JTextField(50);
JScrollPane sp = new JScrollPane(taMessages,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(sp,"Center");
JPanel bp = new JPanel( new FlowLayout());
bp.add(tfInput);bp.add(btnSend);
bp.add(btnExit);
add(bp,"South");
btnSend.addActionListener(this);
btnExit.addActionListener(this);
setSize(500,300);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == btnExit ) {
pw.println("end"); // send end to server so that server know about the termination
System.exit(0);
} else {
// send message to server
pw.println(tfInput.getText());
}
}
public static void main(String args[]) {
// take username from userString name = JOptionPane.showInputDialog(null,"Enter your name :", "Username",
JOptionPane.PLAIN_MESSAGE);
String servername = "localhost";
try {new ChatClient( name ,servername);
} catch(Exception ex) {
out.println( "Error --> " + ex.getMessage());
}
} // end of main
7/30/2019 Stack Using Linklist
16/70
// inner class for Messages Thread
class MessagesThread extends Thread {
public void run() {
String line;
try {
while(true) {
line = br.readLine();taMessages.append(line + "\n");
} // end of while
} catch(Exception ex) {}}
}
} // end of client
OUTPUT:
RESULT: Thus the program is written to implement multi-threaded GUI.
7/30/2019 Stack Using Linklist
17/70
11 SCIENTIFIC CALCULATOR 2.9.2010
AIM:
To write a program to implement scientific calculator using even-driven programming.
ALGORITHM:
Step 1: Start the program.
Step 2: Import the required packages.
Step 3: Create class that extends frame.
Step 4: Create text field and buttons.
Step 5: Add buttons to panel.
Step 6: Add mouse listener and perform necessary operation.
Step 7: Exit the application.
7/30/2019 Stack Using Linklist
18/70
SCIENTIFIC CALCULATOR
PROGRAM:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.ButtonGroup;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;import javax.swing.JOptionPane;
import javax.swing.JPanel;import javax.swing.JRadioButton;import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
public class Calc extends JFrame implements ActionListener,MouseListener //,KeyListener{
private JButton jb_one,jb_two,jb_three,jb_four,jb_five,jb_six,jb_seven,jb_eight,jb_nine,jb_zero;private JButton jb_plus,jb_minus,jb_divide,jb_multiply;
private JButton jb_sin,jb_cos,jb_tan,jb_asin,jb_acos,jb_atan,jb_pie,jb_E;
private JButton jb_decimalpoint,jb_equalto,jb_fact,jb_power,jb_changesign,jb_reciporcal;private JButton jb_todeg,jb_torad,jb_round,jb_CA,jb_CE,jb_Backspace;
private JRadioButton jrb_deg,jrb_rad;
private ButtonGroup jrb_group;
private JTextField jtf_display;
7/30/2019 Stack Using Linklist
19/70
private double tempdisplayNum;
boolean plusPressed,minusPressed,mulPressed,divPressed,equalPressed,powerPressed;
/**
* This constructor forms GUI and add required Compontents
* to listeners.*/
public Calc()
{
super("Scientic Calculator ( Currently running on JVM Version " +
System.getProperty("java.version") + " )");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{
Calc.this.dispose();
System.runFinalization();System.gc();
System.exit(0);
}});
tempdisplayNum = 0;resetAllButton();
equalPressed = false;
/** GUI Formation
*/
JPanel jp_main = new JPanel();jp_main.setLayout(new BorderLayout());
jp_main.setBorder(new EmptyBorder(new Insets(3,5,5,5)));
JPanel jp_top = new JPanel();jp_top.setLayout(new BorderLayout());
JPanel jp_top_down = new JPanel();
jp_top_down.setLayout(new BorderLayout());JPanel jp_top_west = new JPanel();
jb_Backspace = new JButton("BackSpace");
jp_top_west.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));
jp_top_west.add(jb_Backspace);
7/30/2019 Stack Using Linklist
20/70
JPanel jp_top_east = new JPanel();
jp_top_east.setLayout(new FlowLayout(FlowLayout.RIGHT));jtf_display = new JTextField();
jtf_display.setEditable(false);
jtf_display.setHorizontalAlignment( JTextField.RIGHT );jtf_display.setRequestFocusEnabled(false);
jtf_display.setBackground(Color.white);
jrb_deg = new JRadioButton("Degrees");jrb_rad = new JRadioButton("Radian");
jrb_deg.setSelected(true);
jrb_group = new ButtonGroup();
jrb_group.add(jrb_deg);jrb_group.add(jrb_rad);
jp_top_east.add(jrb_deg);
jp_top_east.add(jrb_rad);jp_top_down.add(jp_top_east,BorderLayout.EAST);
jp_top_down.add(jp_top_west,BorderLayout.WEST);
jp_top.setLayout(new BorderLayout());
jp_top.add(jtf_display,BorderLayout.CENTER);jp_top.add(jp_top_down,BorderLayout.SOUTH);
JPanel jp_center = new JPanel();
jp_center.setLayout(new GridLayout(5,7,5,5));
jb_one = new JButton("1");jb_two = new JButton("2");
jb_three = new JButton("3");
jb_four = new JButton("4");jb_five = new JButton("5");
jb_six = new JButton("6");jb_seven = new JButton("7");jb_eight = new JButton("8");
jb_nine = new JButton("9");
jb_zero = new JButton("0");
jb_plus = new JButton("+");jb_minus = new JButton("-");
jb_divide = new JButton("/");
jb_multiply = new JButton("*");jb_sin = new JButton("Sin");
jb_cos = new JButton("Cos");
jb_tan = new JButton("Tan");jb_asin = new JButton("aSin");
jb_acos = new JButton("aCos");
jb_atan = new JButton("aTan");jb_pie = new JButton("PI");
jb_E = new JButton("E");
jb_decimalpoint = new JButton(".");
jb_equalto = new JButton("=");
7/30/2019 Stack Using Linklist
21/70
jb_fact = new JButton("x!");
jb_power = new JButton("x^n");jb_changesign = new JButton("+/-");
jb_reciporcal = new JButton("1/x");
jb_todeg = new JButton("toDeg");jb_torad = new JButton("toRad");
jb_round = new JButton("Round");
jb_CA = new JButton("CA");jb_CE = new JButton("CE");
/**
* Adding Button to Listeners*/
jb_one.addActionListener(Calc.this);
jb_two.addActionListener(Calc.this);jb_three.addActionListener(Calc.this);
jb_four.addActionListener(Calc.this);
jb_five.addActionListener(Calc.this);
jb_six.addActionListener(Calc.this);jb_seven.addActionListener(Calc.this);
jb_eight.addActionListener(Calc.this);jb_nine.addActionListener(Calc.this);
jb_zero.addActionListener(Calc.this);
jb_plus.addActionListener(Calc.this);
jb_minus.addActionListener(Calc.this);jb_divide.addActionListener(Calc.this);
jb_multiply.addActionListener(Calc.this);
jb_sin.addActionListener(Calc.this);jb_cos.addActionListener(Calc.this);
jb_tan.addActionListener(Calc.this);jb_asin.addActionListener(Calc.this);jb_acos.addActionListener(Calc.this);
jb_atan.addActionListener(Calc.this);
jb_pie.addActionListener(Calc.this);
jb_E.addActionListener(Calc.this);jb_decimalpoint.addActionListener(Calc.this);
jb_equalto.addActionListener(Calc.this);
jb_fact.addActionListener(Calc.this);jb_power.addActionListener(Calc.this);
jb_changesign.addActionListener(Calc.this);
jb_reciporcal.addActionListener(Calc.this);jb_todeg.addActionListener(Calc.this);
jb_torad.addActionListener(Calc.this);
jb_round.addActionListener(Calc.this);jb_CA.addActionListener(Calc.this);
jb_CE.addActionListener(Calc.this);
jb_Backspace.addActionListener(Calc.this);
7/30/2019 Stack Using Linklist
22/70
jp_center.add(jb_one);
jp_center.add(jb_two);
jp_center.add(jb_three);jp_center.add(jb_multiply);
jp_center.add(jb_reciporcal);
jp_center.add(jb_sin);jp_center.add(jb_asin);
jp_center.add(jb_four);
jp_center.add(jb_five);
jp_center.add(jb_six);jp_center.add(jb_divide);
jp_center.add(jb_power);
jp_center.add(jb_cos);jp_center.add(jb_acos);
jp_center.add(jb_seven);
jp_center.add(jb_eight);
jp_center.add(jb_nine);jp_center.add(jb_plus);
jp_center.add(jb_changesign);jp_center.add(jb_tan);
jp_center.add(jb_atan);
jp_center.add(jb_zero);
jp_center.add(jb_decimalpoint);jp_center.add(jb_equalto);
jp_center.add(jb_minus);
jp_center.add(jb_fact);jp_center.add(jb_pie);
jp_center.add(jb_E);jp_center.add(jb_CA);jp_center.add(jb_CE);
jp_center.add(jb_round);
jp_center.add(jb_todeg);
jp_center.add(jb_torad);
Container cp = this.getContentPane();
jp_main.add(jp_top,BorderLayout.NORTH);jp_main.add(jp_center,BorderLayout.CENTER);
cp.add(jp_main,BorderLayout.CENTER);
setSize(520,250);/* Packing all Commponent, so spaces are left */
pack();
/* Making Window to appear in Center of Screen */Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getPreferredSize();
setLocation(screenSize.width/2 - (frameSize.width/2),screenSize.height/2 - (frameSize.height/2));
setVisible(true);
7/30/2019 Stack Using Linklist
23/70
this.requestFocus();}
/*** This method is used to reset the condition that
* No plus,minus,multiply,division or power action is going on
* if there is cancel it.*/
public void resetAllButton()
{
plusPressed = false;minusPressed = false;
mulPressed = false;
divPressed = false;powerPressed = false;
}
/*** This method is use to calculate the factorial of
* number of double data type*
* @param Double value
* @return String value
*/public String factorial(double num)
{
int theNum = (int)num;
if (theNum < 1){JOptionPane.showMessageDialog(Calc.this,"Cannot find the factorial of numbers less than
1.","Facorial Error",JOptionPane.WARNING_MESSAGE);
return ("0");
}else
{
for (int i=(theNum -1); i > 1; --i)theNum *= i;
return Integer.toString(theNum);
}}
/**
7/30/2019 Stack Using Linklist
24/70
* This is important method where All action takes places
*/public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();String temptext = jtf_display.getText();
boolean decimalPointFound = false;
double displayNumber = 0;
/**
* Converts String value of jtf_display's to Double value for Calculation
*/try
{
displayNumber = Double.valueOf(jtf_display.getText()).doubleValue();}
catch(NumberFormatException nfe) {}
/*** Checks if equal button is pressed
*/if(equalPressed)
{
jtf_display.setText("");
equalPressed = false;}
if(s.equals("1"))
jtf_display.setText(jtf_display.getText()+"1");if(s.equals("2"))jtf_display.setText(jtf_display.getText()+"2");
if(s.equals("3"))
jtf_display.setText(jtf_display.getText()+"3");
if(s.equals("4"))jtf_display.setText(jtf_display.getText()+"4");
if(s.equals("5"))
jtf_display.setText(jtf_display.getText()+"5");if(s.equals("6"))
jtf_display.setText(jtf_display.getText()+"6");
if(s.equals("7"))jtf_display.setText(jtf_display.getText()+"7");
if(s.equals("8"))
jtf_display.setText(jtf_display.getText()+"8");if(s.equals("9"))
jtf_display.setText(jtf_display.getText()+"9");
if(s.equals("0") && !temptext.equals(""))
7/30/2019 Stack Using Linklist
25/70
jtf_display.setText(jtf_display.getText()+"0");
if(s.equals("E"))
jtf_display.setText(Double.toString(Math.E));
if(s.equals("PI"))jtf_display.setText(Double.toString(Math.PI));
if(s.equals("toDeg"))
jtf_display.setText(Double.toString(Math.toDegrees(displayNumber)));if(s.equals("toRad"))
jtf_display.setText(Double.toString(Math.toRadians(displayNumber)));
if(s.equals("CE"))jtf_display.setText("");
if(s.equals("CA"))
{resetAllButton();
jtf_display.setText("");
}
if(s.equals("."))
{
for (int i =0; i < temptext.length(); ++i)
{if(temptext.charAt(i) == '.')
{
decimalPointFound = true;continue;
}}if(!decimalPointFound && temptext.length()==0)
jtf_display.setText("0.");
if(!decimalPointFound && temptext.length()!=0)
jtf_display.setText(jtf_display.getText()+".");}
/*** Calulation of sin,cos etc
*/
if(s.equals("Sin")){
if(jrb_deg.isSelected())
jtf_display.setText(Double.toString(Math.sin((displayNumber*Math.PI)/180)));else
{
jtf_display.setText(Double.toString(Math.sin(displayNumber)));
// decimalPointpressed
7/30/2019 Stack Using Linklist
26/70
}
}
if(s.equals("Cos"))
{if(jrb_deg.isSelected())
jtf_display.setText(Double.toString(Math.cos((displayNumber*Math.PI)/180)));
else{
jtf_display.setText(Double.toString(Math.cos(displayNumber)));
// decimalPointpressed
}}
if(s.equals("Tan")){
if(jrb_deg.isSelected())
jtf_display.setText(Double.toString(Math.tan((displayNumber*Math.PI)/180)));
else{
jtf_display.setText(Double.toString(Math.tan(displayNumber)));// decimalPointpressed
}
}
if(s.equals("aSin"))
{
if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.asin((displayNumber*Math.PI)/180)));
else{
jtf_display.setText(Double.toString(Math.asin(displayNumber)));
// decimalPointpressed
}
}
if(s.equals("aCos"))
{if(jrb_deg.isSelected())
jtf_display.setText(Double.toString(Math.acos((displayNumber*Math.PI)/180)));
else{
jtf_display.setText(Double.toString(Math.acos(displayNumber)));
// decimalPointpressed}
}
if(s.equals("aTan"))
7/30/2019 Stack Using Linklist
27/70
{
if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.atan((displayNumber*Math.PI)/180)));
else
{jtf_display.setText(Double.toString(Math.atan(displayNumber)));
// decimalPointpressed
}}
/**
* Calculation of "/""*""+""-"*/
if(s.equals("*"))
{resetAllButton();
mulPressed = true;
try
{tempdisplayNum = displayNumber;
}catch(NumberFormatException mule)
{ tempdisplayNum = 0; }
jtf_display.setText("");
}
if(s.equals("+"))
{resetAllButton();
plusPressed = true;try{
tempdisplayNum = displayNumber;
}
catch(NumberFormatException pluse){ tempdisplayNum = 0; }
jtf_display.setText("");
}
if(s.equals("-"))
{resetAllButton();
minusPressed = true;
try{
tempdisplayNum = displayNumber;
}
catch(NumberFormatException sube)
7/30/2019 Stack Using Linklist
28/70
{ tempdisplayNum = 0; }
jtf_display.setText("");}
if(s.equals("/")){
resetAllButton();
divPressed = true;try
{
tempdisplayNum = displayNumber;
}catch(NumberFormatException dive)
{ tempdisplayNum = 0; }
jtf_display.setText("");}
/**
* It calculate power*/
if(s.equals("x^n")){
powerPressed = true;
try
{tempdisplayNum = displayNumber;
}
catch(NumberFormatException dive){ tempdisplayNum = 0; }
jtf_display.setText("");}
/**
* Events after "=" is pressed
*/if(s.equals("="))
{
if(mulPressed)jtf_display.setText(Double.toString(tempdisplayNum*displayNumber));
if(plusPressed)
jtf_display.setText(Double.toString(tempdisplayNum+displayNumber));if(minusPressed)
jtf_display.setText(Double.toString(tempdisplayNum-displayNumber));
if(divPressed)jtf_display.setText(Double.toString(tempdisplayNum/displayNumber));
if(powerPressed)
jtf_display.setText(Double.toString(Math.pow(tempdisplayNum,displayNumber)));
7/30/2019 Stack Using Linklist
29/70
resetAllButton();
equalPressed = true;}
/*** Events for more functions "1/x""+/-""x!""Round"
*/
if(s.equals("1/x"))jtf_display.setText(Double.toString(1/displayNumber));
if(s.equals("+/-") && displayNumber!=0)
jtf_display.setText(Double.toString(-displayNumber));
if(s.equals("x!"))jtf_display.setText(factorial(displayNumber));
if(s.equals("Round"))
jtf_display.setText(Double.toString(Math.round(displayNumber)));
/**
* For BackSpace Event
*/if(s.equals("BackSpace"))
{String temptextt = jtf_display.getText();
if(!temptextt.equals(""))
jtf_display.setText(temptextt.substring(0, temptextt.length() - 1));
}
}
public void mouseClicked(MouseEvent me)
{}
public void mouseEntered(MouseEvent me)
{
}
public void mouseExited(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me) {}public void mousePressed(MouseEvent me) {}
public static void main(String args[])
{
7/30/2019 Stack Using Linklist
30/70
try
{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e){}
new Calc();
}}
OUTPUT:
RESULT:Thus the program is written to implement Scientific Calculator.
13 PRODUCER CONSUMER USING MULTITHREAD 9.9.2010
7/30/2019 Stack Using Linklist
31/70
AIM:
To design a thread safe implementation of queue class.
ALGORITHM:
1.The producer creates tasks and inserts them into work queue.
2.The consumer thread pick up task queue and execute then.
3.Simple instances of this paradigm in which the task queue can hold only one task,which may be sort or
long but it is typically hava bounded size.
4.In this simple model,the producer thread can estimate the time taken for consumer work and insert newwork in shared buffer.
5.Several possibilities exist in which the producer thread must not overwrite the shared buffer when the
previous task has not been picked by consumer thread.
6.Also,the consumer thread must not pick up tasks until there is something present in the shared data
structure and individual consumer thread picks up tasks one at a time.
7.Stop
PRODUCER CONSUMER
7/30/2019 Stack Using Linklist
32/70
PROGRAM:
class Q {int n;
boolean valueSet = false;
synchronized int get() {if(!valueSet)try {
wait();
} catch(InterruptedException e) {System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);valueSet = false;
notify();
return n;
}synchronized void put(int n) {
if(valueSet)
try {wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");}
this.n = n;
valueSet = true;System.out.println("Put: " + n);
notify();}
}class Producer implements Runnable {
Q q;
Producer(Q q) {this.q = q;
new Thread(this, "Producer").start();
}public void run() {
int i = 0;
while(true) {q.put(i++);}
}
}class Consumer implements Runnable {
Q q;
Consumer(Q q) {this.q = q;
7/30/2019 Stack Using Linklist
33/70
new Thread(this, "Consumer").start();
}public void run() {
while(true) {
q.get();}
}
}class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);new Consumer(q);
System.out.println("Press Control-C to stop.");
}}
OUTPUT:
C:\Program Files\Java\jdk1.6.0_17\bin>javac PCFixed.java
C:\Program Files\Java\jdk1.6.0_17\bin>java PCFixed
Put: 3148
Got: 3148Put: 3149
Got: 3149
Put: 3150Got: 3150
Put: 3151Got: 3151
Put: 3152Got: 3152
Put: 3153
Got: 3153Put: 3154
Got: 3154
RESULT:
Thus the program is written to implement Producer Consumer problem.
14 FIBONICCI AND PRIME USING MULTITHREAD 17.9.2010
7/30/2019 Stack Using Linklist
34/70
AIM:
To Write Program to develop multithreaded concept using pipes
ALGORITHM:
Step 1:Start the program
Step 2:Import required packages
Step3:Declare necessary variables and function
Step 4:Create object parameters pr and pw to pass the values
Step5: Using thread1()Function find the parameters find prime numbers and Fibonacci series
And numbers common both the series.
Step 6:Stop the program
MULTITHREADED
PROGRAM:
7/30/2019 Stack Using Linklist
35/70
import java.io.*;
import java.util.*;
class MyThread1 extends Thread
{private PipedReader pr;
private PipedWriter pw;
MyThread1(PipedReader pr, PipedWriter pw)
{this.pr = pr;
this.pw = pw;
}
public void run()
{
try{
int i;
for (i=1;i
7/30/2019 Stack Using Linklist
36/70
{
this.pr = pr;this.pw = pw;
}
public void run()
{
try{
int f1, f2 = 1, f3 = 1;
for (int i = 1; i
7/30/2019 Stack Using Linklist
37/70
while ((item2 = pr2.read()) != -1){
char ch2=((char) item2);System.out.print(Character.toString(ch2));
list2.add(Character.toString(ch2));
}pr2.close();
System.out.println("Elements common to both lists are:");
list1.retainAll(list2);for(int i=0;i
7/30/2019 Stack Using Linklist
38/70
AIM:
To design a java interface for stack ADT.
ALGORITHM:
Step 1: Start the program
Step 2: create :: Stack acreate an empty stackStep 3: push :: a->Stack a->Stack apush an element on the stack
Step 4: pop :: Stack a->(a.,Stack a)pop an element off the stack
Step 5: empty :: Stack a->Booltells whether stack is empty
Step 6: pop(push x s)=(x,s)
Step 7: pop(create)error
Step 8: The interface to the stack ADT is defined as follows(file=MyStack.java);
Step 9: A simple stack testing class(file=StackTest.java)
Step 10:End the program
INTERFACE FOR STACK ADT
PROGRAM:
7/30/2019 Stack Using Linklist
39/70
import java.util.*;
interface adt
{
public void push(int c);
public int pop();
public boolean isempty();public boolean isfull();
public void display();
}
class st implements adt
{
int top;
int [] st=new int[20];
st()
{
top=-1;
}public boolean isempty()
{
return(top==-1);
}
public boolean isfull()
{
return(top>=20);
}
public void push(int c)
{
if(isfull())
{
System.out.println("STACK IS FULL");
}
else
{
top++;
st[top]=c;
}
}
public int pop(){
if(isempty())
{
System.out.println("STACK IS EMPTY");
return 0;
}
else
7/30/2019 Stack Using Linklist
40/70
7/30/2019 Stack Using Linklist
41/70
case 2:
element=s.pop();
if(element!=0)
System.out.println("THE POPPED CHARECTER IS:"+element);
break;
case 3:
s.display();break;
case 4:
break;
}
}while(choice
7/30/2019 Stack Using Linklist
42/70
3
STACK IS EMPTY
1.PUSH 2.POP 3. DISPLAY 4. EXIT
ENTER UR CHOICE:
4
OUTPUT 2:
1.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:
1
ENTER AN INTEGER TO PUSH:
W
Integer values only allowed: java.util.InputMismatchException
1.PUSH 2.POP 3. DISPLAY 4. EXIT
ENTER UR CHOICE:
4
RESULT:
Thus the program for stack ADT using java interface was written and expected output is achieved.
4 QUEUE 28.7.2010
7/30/2019 Stack Using Linklist
43/70
AIM:
To develop a Java program with simple Queue using Array
ALGORITHM:
Step 1: Declare a class queue in which implements the variable
maxsize ,fronts,rear,nitems
Step 2: Declare a parameterized constructor
Step 3: Get the function insert () to put item at rear end of queue
Step 4:Get function remove to take item from front of queue
Step 5: Get the function peek front() to peek item at front of queue
Step 6: Declare Boolean to check queue size
Step 7: Declare main imside class queue app
Step 8: Declare an object thequeue
Step 9: call insert and remove functions
Step 10:stop the program
QUEUE USING ARRAY
PROGRAM:
7/30/2019 Stack Using Linklist
44/70
class Queue
{
private int maxSize;private long[] queArray;
private int front;
private int rear;private int nItems;
public Queue(int s) // constructor
{maxSize = s;
queArray = new long[maxSize];
front = 0;rear = -1;
nItems = 0;
}
public void insert(long j) // put item at rear of queue
{if(rear == maxSize-1) // deal with wraparound
rear = -1;
queArray[++rear] = j; // increment rear and insert
nItems++; // one more item}
public long remove() // take item from front of queue{
long temp = queArray[front++]; // get value and incr frontif(front == maxSize) // deal with wraparoundfront = 0;
nItems--; // one less item
return temp;
}
public long peekFront() // peek at front of queue
{return queArray[front];
}
public boolean isEmpty() // true if queue is empty
{
return (nItems==0);}
public boolean isFull() // true if queue is full
{
7/30/2019 Stack Using Linklist
45/70
return (nItems==maxSize);
}
public int size() // number of items in queue
{return nItems;
}
}
class QueueApp
{
public static void main(String[] args){
Queue theQueue = new Queue(5); // queue holds 5 items
theQueue.insert(10); // insert 4 itemstheQueue.insert(20);
theQueue.insert(30);
theQueue.insert(40);
theQueue.remove(); // remove 3 itemstheQueue.remove(); // (10, 20, 30)
theQueue.remove();theQueue.insert(50); // insert 4 more items
theQueue.insert(60); // (wraps around)
theQueue.insert(70);
theQueue.insert(80);while( !theQueue.isEmpty() ) // remove and display
{
long n = theQueue.remove(); // (40, 50, 60, 70, 80)System.out.print(n);
System.out.print("");}System.out.println("");
}
}// EXTRA PROGRAM
import java.io.*;
import java.util.*;
public class queue
{
LinkedList list;
int num;
public static void main(String args[])
{
queue q=new queue();
}
public queue()
7/30/2019 Stack Using Linklist
46/70
{
try
{
list=new LinkedList();
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter the number of element");
if((num=Integer.parseInt(d.readLine()))==0)
{
System.out.println("YOU entered zero\null");
System.exit(0);
}
else
{
System.out.println("Enter the element");
for(int i=0;i
7/30/2019 Stack Using Linklist
47/70
AIM:
To develop a simple paint like program that can draw basic graphical primitives in different
dimensions and colors
ALGORITHM:
Step 1 : Import all packages
Step 2 : Declare all necessary variables
Step 3: Create drawing class that calls frame class
Step4 : Create frame and include all icons of line ,oval,rectangle etc
Step 5: Draw all shapes using tools created
Step 6: Close the application
PROGRAM:
//Shape.java
7/30/2019 Stack Using Linklist
48/70
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Stroke;
public abstract class Shape
{ private int x1;
private int y1;
private Paint paint;
private Stroke stroke;
// Class constructor with no argument
public Shape ()
{
x1 = 0;
y1 = 0;
paint = Color.BLACK;}
// Class constructor with three argument
public Shape( int x1Value , int y1Value , Paint paintValue , Stroke strokeValue )
{
x1 = x1Value;
y1 = y1Value;
paint = paintValue;
stroke = strokeValue;
}
// Each class that inherites this class must implement this method
// because this method is an abstract method
public abstract void draw( Graphics2D g2d );
public int getx1()
{
return x1;
}
public void setx1( int x1Value){
x1 = ( x1Value > 0 ? x1Value : 0 );
}
public int gety1()
{
return y1;
7/30/2019 Stack Using Linklist
49/70
}
public void sety1( int y1Value )
{
y1 = ( y1Value > 0 ? y1Value : 0 );
}
public Paint getPaint()
{
return paint;
}
public void setPaint( Paint paintValue )
{
paint = paintValue;
}
public void setStroke( Stroke strokeValue ){
stroke = strokeValue;
}
public Stroke getStroke()
{
return stroke;
}
} // end class Shape
//Drawing.java
import javax.swing.JFrame;
public class Drawing
{
public static void main (String[] args)
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setSize ( 600 , 600 );
frame.setVisible ( true );
}
} // end class Drawing
7/30/2019 Stack Using Linklist
50/70
//DrawPanel.java
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;import java.awt.Paint;
import java.awt.GradientPaint;
import java.awt.BasicStroke;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
public class DrawPanel extends JPanel
{
private Shape shapes[]; // Holds the shapes that the user has drawn
private Shape currentShape; // Holds the current shape the user is drawing
private Color color1; // If user uses Gradient , it holds the first color
private Color color2; // If user uses Gradient , it holds the second color
private Paint currentPaint; // Holds the current paint Pattern
private Stroke currentStroke; // Holds the current stroke pattern
private int lineWidth; // Holds the line width as a parameter for currentStroke
private int dashLength; // Holds the dash lenght as a parameter for currentStroke
private int shapeCount; // Holds the number of shapes the user has drawn
private int shapeType; // Holds the current shapeType ( Line , Retangle or oval )
private int x1 , y1 , x2 , y2; // Holds necessary points
private boolean filledShape; // Holds whether to draw a fill or not
private boolean useGradient; // Holds whether to use gradient or not
private boolean dashed; // Holds whether to draw dashed lines or not
private final int LINE = 0, // Constants for identifying how to draw different shapes
RECT = 1,
OVAL = 2;
// Class constructor
public DrawPanel()
{
shapes = new Shape[ 100 ];
currentShape = null;
color1 = Color.BLACK;
color2 = Color.BLACK;
currentPaint = Color.BLACK;
currentStroke = null;
7/30/2019 Stack Using Linklist
51/70
lineWidth = 1;
dashLength = 1;
shapeCount = 0;
shapeType = 0;
x1 = 0;
y1 = 0;
x2 = 0;y2 = 0;
filledShape = false;
useGradient = false;
dashed = false;
// Set the DrawPanel's background color
this.setBackground ( Color.WHITE );
// Register event listeners for DrawPanel
this.addMouseMotionListener ( new mouseHandler() );
this.addMouseListener ( new mouseHandler() );
} // end constructor
public void paintComponent( Graphics g )
{
super.paintComponent ( g );
// Cast Graphics object "g" to Graphics2D
Graphics2D g2d = ( Graphics2D ) g;
int i = 0;
// Draw preceding shapes that the user has drawn
while ( i < shapeCount )
{
shapes[ i ].draw ( g2d );
i++;
}
// Draw the current shape that user has just drawnif ( currentShape != null )
currentShape.draw ( g2d );
} // end method paintComponent
public void setShapeType( int shapeTypeValue )
{
7/30/2019 Stack Using Linklist
52/70
shapeType = shapeTypeValue;
}
public void setCurrentPaint( Paint paintValue )
{
currentPaint = paintValue;
}
public void setStroke( Stroke strokeValue )
{
currentStroke = strokeValue;
}
public void setFilledShape( boolean fillValue)
{
filledShape = fillValue;
}
public void setUseGradient( boolean useGradientValue )
{
useGradient = useGradientValue;
}
public void setColor1( Color color1Value )
{
color1 = color1Value;
}
public void setColor2( Color color2Value )
{
color2 = color2Value;
}
public void setDashed( boolean dashValue )
{
dashed = dashValue;
}
public void setLineWidth( int lineWidthValue ){
lineWidth = lineWidthValue;
}
public void setDashLength( int dashLenghtValue )
{
dashLength = dashLenghtValue;
7/30/2019 Stack Using Linklist
53/70
}
public void clearLastShape()
{
if ( shapeCount > 0 ){
shapeCount--;
currentShape=null;
// Invoke method repaint to refresh the DrawPanel
this.repaint ();
}
}
public void clearDrawing()
{
shapeCount = 0;
currentShape = null;
// Invoke method repaint to refresh the DrawPanel
this.repaint ();
}
// Inner class for handling mouse events
private class mouseHandler extends MouseAdapter implements MouseMotionListener
{
public void mousePressed( MouseEvent event )
{
// set the shape's first point
if ( event.isAltDown () == false && event.isMetaDown () == false){
x1 = event.getX ();
y1 = event.getY ();
}
}
public void mouseReleased( MouseEvent event )
{
// Put the drew shape into the array "shapes"
if ( event.isAltDown () == false && event.isMetaDown () == false){
shapes [ shapeCount ] = currentShape;
shapeCount++;
}
}
public void mouseDragged( MouseEvent event )
7/30/2019 Stack Using Linklist
54/70
{
if ( event.isAltDown () == false && event.isMetaDown () == false)
{
// Set the shape's second point
x2 = event.getX ();
y2 = event.getY ();
// Check whether user wants to use gradient
if ( useGradient == true )
currentPaint = new GradientPaint( 0 , 0 , color1 , 50 , 50 , color2 , true );
else
currentPaint = color1;
// Check whether user wants to draw dashed lines
if ( dashed == true ) {
float dashLenghtArray[]={ dashLength };
currentStroke = new BasicStroke( lineWidth , BasicStroke.CAP_ROUND ,BasicStroke.JOIN_ROUND , 10 , dashLenghtArray , 0 );
}
else
currentStroke = new BasicStroke( lineWidth );
// Create the appropriate shape according to the user selection
switch ( shapeType )
{
case LINE:
currentShape = new Line( x1 , y1 , x2 , y2 , currentPaint , currentStroke);
break;
case RECT:
currentShape = new Rectangle( x1 , y1 , x2 , y2 , currentPaint , currentStroke , filledShape
);
break;
case OVAL:
currentShape = new Oval( x1 , y1 , x2 , y2 , currentPaint , currentStroke , filledShape );
break;
}
DrawPanel.this.repaint ();
} // end if
} // end method mouseDragged
} // end class MouseHandler
7/30/2019 Stack Using Linklist
55/70
} // end class DrawPanel
//Line.java
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.Paint;
public class Line extends Shape
{
private int x2;
private int y2;
// Class constructor with no argument
public Line ()
{
super();x2 = 0;
y2 = 0;
}
// Class constructor with five argument
public Line( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , Stroke
strokeValue )
{
super ( x1Value , y1Value , paintValue , strokeValue );
x2= x2Value;
y2 = y2Value;
}
// Override abstract method "draw" inherited from class "Shape" to draw a line
public void draw( Graphics2D g2d )
{
g2d.setPaint ( super.getPaint () );
g2d.setStroke ( super.getStroke () );
g2d.drawLine ( super.getx1 () , super.gety1 () , x2 , y2 );
}
} // end class Line
//Oval.java
import java.awt.Graphics2D;
import java.awt.Color;
7/30/2019 Stack Using Linklist
56/70
import java.awt.Stroke;
import java.awt.Paint;
public class Oval extends Shape
{
private int width;private int height;
private boolean fill;
// Class constructor with no argument
public Oval ()
{
super();
width = 1;
height = 1;
fill = false;
}
// Class constructor with six argument
public Oval( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , Stroke
strokeValue , boolean fillValue )
{
super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ? y1Value : y2Value ,
paintValue , strokeValue );
width = Math.abs ( x1Value - x2Value );
height = Math.abs ( y1Value - y2Value );
fill = fillValue;
}
// Override abstract method "draw" inherited from class "Shape" to draw an oval
public void draw ( Graphics2D g2d )
{
g2d.setPaint ( super.getPaint () );
g2d.setStroke ( super.getStroke () );
if ( fill == true )
g2d.fillOval ( super.getx1 () , super.gety1 () , width , height );
elseg2d.drawOval ( super.getx1 () , super.gety1 () , width , height );
}
} // end class Oval
7/30/2019 Stack Using Linklist
57/70
//DrawFrame.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;import java.awt.event.ItemEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class DrawFrame extends JFrame
{
private DrawPanel drawPanel;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JButton undoButton;
private JButton clearButton;
private JButton firstColorButton;
private JButton secondColorButton;
private JComboBox shapeComboBox;
private JCheckBox fillCheckBox;
private JCheckBox gradientCheckBox;
private JCheckBox dashCheckBox;
private JLabel shapesLabel;
private JLabel widthLabel;
private JLabel lengthLabel;private JTextField widthTextField;
private JTextField dashLengthTextField;
private final String shapeNames[] = { "Line" , "Rectangle" ,"Oval" };
// Class constructor
public DrawFrame ()
7/30/2019 Stack Using Linklist
58/70
{
// Set the title of JFrame
setTitle ( "Drawing Application" );
// Create a JPanel as a container for GUI components in first row
panel1 = new JPanel();
// Set the layout of panel1
panel1.setLayout ( new FlowLayout( FlowLayout.CENTER ) );
// Create a JPanel as a container for GUI components in second row
panel2 = new JPanel();
// Set the layout of panel2
panel2.setLayout ( new FlowLayout( FlowLayout.CENTER ) );
// Create a JPanel to hold panel1 , panel2 and panel3
panel3 = new JPanel();
// Set the layout of panel4
panel3.setLayout ( new GridLayout( 2,1,0,0) );
// Create button "Undo" and add it to the panel
undoButton = new JButton();
undoButton.setText( "Undo" );
undoButton.addActionListener (
// Create and register an ActionListener
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
drawPanel.clearLastShape ();
}
}
);
panel1.add ( undoButton );
// Create button "Clear" and add it to panel1clearButton = new JButton();
clearButton.setText( "Clear" );
clearButton.addActionListener (
// Create and register an ActionListener
new ActionListener()
{
public void actionPerformed( ActionEvent event )
7/30/2019 Stack Using Linklist
59/70
{
drawPanel.clearDrawing ();
}
}
);
panel1.add ( clearButton );
// Create label "shapesLabel" and add it to panel1
shapesLabel = new JLabel();
shapesLabel.setText ( "Shapes:" );
panel1.add ( shapesLabel );
// Create a combobox that contains shape names and add it to panel1
shapeComboBox = new JComboBox( shapeNames);
shapeComboBox.setMaximumRowCount ( 3 );
shapeComboBox.addItemListener (
// Create and register an ItemLsitener
new ItemListener(){
public void itemStateChanged( ItemEvent event )
{
if ( event.getStateChange () == ItemEvent.SELECTED )
drawPanel.setShapeType ( shapeComboBox.getSelectedIndex () );
}
}
);
panel1.add ( shapeComboBox );
// Create checkbox "fillCheckBox" and add it to panel1
fillCheckBox = new JCheckBox();
fillCheckBox.setText ( "Filled" );
fillCheckBox.addItemListener (
// Create and register an ItemListener
new ItemListener()
{
public void itemStateChanged( ItemEvent event )
{
drawPanel.setFilledShape ( fillCheckBox.isSelected () );}
}
);
panel1.add ( fillCheckBox );
// Create checkbox "gradientCheckBox" and add it to panel2
7/30/2019 Stack Using Linklist
60/70
gradientCheckBox = new JCheckBox();
gradientCheckBox.setText ( "Use Gradient" );
gradientCheckBox.addItemListener (
// Create and register an ItemListener
new ItemListener()
{
public void itemStateChanged( ItemEvent event ){
drawPanel.setUseGradient ( gradientCheckBox.isSelected () );
}
}
);
panel2.add ( gradientCheckBox );
// Create button "firstColor" and add it to panel2
firstColorButton = new JButton();
firstColorButton.setText ( "1st Color..." );
firstColorButton.addActionListener (// Create and register an ActionListener
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
Color color = Color.BLACK;
color = JColorChooser.showDialog ( null , "Color Chooser" , color );
if ( color == null)
color = color.BLACK;
drawPanel.setColor1 ( color );
}
}
);
panel2.add ( firstColorButton );
// Create button "secondColor" and add it to panel2
secondColorButton = new JButton();
secondColorButton.setText ( "2nd Color..." );secondColorButton.addActionListener (
// Create and register an ActionListener
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
Color color = Color.BLACK;
7/30/2019 Stack Using Linklist
61/70
color = JColorChooser.showDialog ( null , "Color Chooser" , color );
if ( color == null)
color = color.BLACK;
drawPanel.setColor2 ( color );}
}
);
panel2.add ( secondColorButton );
// Create label "widthLabel" and set its properties
widthLabel = new JLabel();
widthLabel.setText ( "Line width:" );
panel2.add ( widthLabel );
// Create text field "widthTextField" and set its propertieswidthTextField = new JTextField();
widthTextField.addKeyListener(
// Create and register an KeyListener
new KeyAdapter()
{
public void keyReleased( KeyEvent e)
{
int lineWidth;
try
{
lineWidth = Integer.parseInt ( widthTextField.getText () );
if ( lineWidth < 1 || lineWidth > 20 )
throw new NumberFormatException();
drawPanel.setLineWidth ( lineWidth );
}
catch ( NumberFormatException exception )
{
JOptionPane.showMessageDialog( null , "Please enter an integer between 1 to 20" ,"Error" , JOptionPane.INFORMATION_MESSAGE );
widthTextField.setText( "" );
}
}
}
);
widthTextField.setColumns ( 2 );
7/30/2019 Stack Using Linklist
62/70
panel2.add ( widthTextField );
// create label "lenghtLabel" and set its properties
lengthLabel = new JLabel();
lengthLabel.setText ( "Dash length:" );
panel2.add ( lengthLabel );
// Create text field "dashLenghtTextField" and set its properties
dashLengthTextField = new JTextField();
dashLengthTextField.setColumns ( 2 );
dashLengthTextField.addKeyListener(
// Create and register an KeyListener
new KeyAdapter()
{
public void keyReleased( KeyEvent e)
{
int dashLength;
try
{
dashLength = Integer.parseInt ( dashLengthTextField.getText () );
if ( dashLength < 1 || dashLength > 50 )
throw new NumberFormatException();
drawPanel.setDashLength ( dashLength );
}
catch ( NumberFormatException exception )
{
JOptionPane.showMessageDialog( null , "Please enter an integer between 1 to 50" ,
"Error" , JOptionPane.INFORMATION_MESSAGE );
dashLengthTextField.setText( "" );
}
}
}
);
panel2.add ( dashLengthTextField );
// Create check box "dashCheckBox" and set its propertiesdashCheckBox = new JCheckBox();
dashCheckBox.setText ( "Dashed" );
dashCheckBox.addItemListener (
// Create and register an ItemLitener
new ItemListener()
{
public void itemStateChanged( ItemEvent event )
7/30/2019 Stack Using Linklist
63/70
{
drawPanel.setDashed ( dashCheckBox.isSelected () );
}
}
);
panel2.add ( dashCheckBox );
// Add panel1 to panel3
panel3.add ( panel1 );
// add panel2 to panel3
panel3.add ( panel2 );
// Add panel3 to the south region of JFrame
this.add ( panel3 , BorderLayout.NORTH );
// Create an object of type DrawPanel
drawPanel = new DrawPanel();
// Add "DrawPanel" object to JFrame
this.add ( drawPanel );
} // end constructor
} // end class DrawFrame
//Rectangle.java
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Stroke;
import java.awt.Paint;
public class Rectangle extends Shape
{
private int width;private int height;
private boolean fill;
// Class constructor with no argument
public Rectangle ()
{
super();
7/30/2019 Stack Using Linklist
64/70
width = 1;
height = 1;
fill = false;
}
// Class constructor with six argument
public Rectangle( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , StrokestrokeValue , boolean fillValue )
{
super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ? y1Value : y2Value ,
paintValue , strokeValue );
width = Math.abs ( x1Value - x2Value );
height = Math.abs ( y1Value - y2Value );
fill = fillValue;
}
// Override abstract method "draw" inherited from class "Shape" to draw a rectangle
public void draw ( Graphics2D g2d ){
g2d.setPaint ( super.getPaint () );
g2d.setStroke ( super.getStroke () );
if ( fill == true )
g2d.fillRect ( super.getx1 () , super.gety1 () , width , height );
else
g2d.drawRect ( super.getx1 () , super.gety1 () , width , height );
}
} // end class Rectangle
OUTPUT:
7/30/2019 Stack Using Linklist
65/70
RESULT:Thus the program is written to implement simple paint like program.
OUTPUT:
C:\Documents and Settings\Administrator\Desktop>cd C:\Program Files\Java\jdk1.5.
0_03\bin
7/30/2019 Stack Using Linklist
66/70
C:\Program Files\Java\jdk1.5.0_03\bin>javac Shape.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac Point.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac circle.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac Cylinder.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac Rectangle.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac RectangularSolid.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac ShapeTest.java
C:\Program Files\Java\jdk1.5.0_03\bin>java ShapeTest
PRINT THE SHAPES AS AN ARRAY OF SHAPE
Circle: Center = [22, 8]; Radius = 3.5, ID: 3
Area = 38.48451000647496
Volume = 0.0
Circle: Center = [23, 9]; Radius = 3.6, ID: 8
Area = 40.71504079052372
Volume = 0.0
Circle: Center = [24, 10]; Radius = 3.7, ID: 13
Area = 43.00840342764427
Volume = 0.0
Cube: Center = [10, 4]; Length = 3.0, Width = 3.0; Height = 3.0, ID: 11
Area = 54.0
Volume = 27.0
Cube: Center = [8, 9]; Length = 4.0, Width = 4.0; Height = 4.0, ID: 15
Area = 96.0
Volume = 64.0
Cylinder: Center = [10, 10]; Radius = 3.3; Height = 10.0, ID: 4
Area = 275.76900313211206
Volume = 342.11943997592846
Cylinder: Center = [20, 20]; Radius = 3.4; Height = 12.0, ID: 9
Area = 328.9875826839231
Volume = 435.8017329059761
Cylinder: Center = [30, 30]; Radius = 3.5; Height = 14.0, ID: 14
Area = 384.84510006474966
Volume = 538.7831400906495
7/30/2019 Stack Using Linklist
67/70
Point: [7, 11], ID: 2
Area = 0.0
Volume = 0.0
Point: [8, 12], ID: 6
Area = 0.0
Volume = 0.0
Point: [9, 13], ID: 12
Area = 0.0
Volume = 0.0
Rectangle: Center = [6, 8]; Length = 3.0, Width = 4.0, ID: 1
Area = 12.0
Volume = 0.0
RectangularSolid: Center = [6, 8]; Length = 3.0, Width = 4.0; Height = 2.0, ID:
5
Area = 52.0
Volume = 24.0
Square: Center = [7, 9]; Length = 2.0, Width = 2.0, ID: 7
Area = 4.0
Volume = 0.0
Square: Center = [5, 7]; Length = 6.0, Width = 6.0, ID: 10Area = 36.0
Volume = 0.0
RESULT:
Thus the program to demonstrate dynamic polymorphism using java was written and
output is achieved.
OUTPUT:
E:\java>java LinkedListExample
Linked List Example!
Linked list data: 11 22 33 44
7/30/2019 Stack Using Linklist
68/70
Linked list size: 4
Adding data at 1st location: 55
Now the list contain: 55 11 22 33 44
Now the size of list: 5
Adding data at last location: 66
Now the list contain: 55 11 22 33 44 66
Now the size of list: 6Adding data at 3rd location: 55
Now the list contain: 55 11 99 22 33 44 66
Now the size of list: 7
First data: 55
Last data: 66
Data at 4th position: 22
Data removed from 1st location: 55
Now the list contain: 11 99 22 33 44 66
Now the size of list: 6
Data removed from last location: 66
Now the list contain: 11 99 22 33 44Now the size of list: 5
Data removed from 2nd location: 99
Now the list contain: 11 22 33 44
Now the size of list: 4
Linked list is empty
RESULT:
Thus the program was executed successfully and output obtained was verified
5 COMPLEX NUMBER 28.7.2010
7/30/2019 Stack Using Linklist
69/70
AIM:
To create a java code to get number as input and write itin complex form and find addition
,subtarction,and multiplication forsuch two complexnumbers.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the necessary member variables and member functions.
Step 3: Using getvalue() function get number to write it in complex form.
Step 4: Using addition() function find the sum of two complex numbers by adding the real part of
complex number and imaginary part of the complex numbers.
Step 5: Similar to addition use subtarction() function,subtract the real part of one with real part of another
complex number and imaginary part of one with imaginary part of another complex number.
Step 6: Using multiplication() function find multiplie of two complex numbers.
Step 7: Print all the function values.
Step 8:Stop the program.
2 STACK ADT 21.7.2010
7/30/2019 Stack Using Linklist
70/70
AIM:
To design a java interface for stack ADT.
ALGORITHM:
Step 1: Start the program
Step 2: create :: Stack acreate an empty stack
Step 3: push :: a->Stack a->Stack apush an element on the stack
Step 4: pop :: Stack a->(a.,Stack a)pop an element off the stack
Step 5: empty :: Stack a->Booltells whether stack is empty
Step 6: pop(push x s)=(x,s)
Step 7: pop(create)error
Step 8: The interface to the stack ADT is defined as follows(file=MyStack.java);
Step 9: A simple stack testing class(file=StackTest.java)
Step 10:End the program