Download WEEK:5-A AIM: write a java program to implement stack using adt

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
WEEK:5-A AIM: write a java program to implement stack using adt.
File name: Edit stackadt.java
Source code: //import io package// import java.io.*; //stack capable to store 4
elements class Stack { int max,top; int no[]; public Stack() { no=new int[5]; top=-1;
max=5; } public void push(int n) { if(top<max-1) { no[++top]=n; } else
System.out.println("Stack full.."); } public int pop() { int val; if(top==-1) {
System.out.println("Stack is Empty..."); return -1; } else { val=no[top--]; } return
val; } public void print() { System.out.println("Stack elements are.."); for(int
i=0;i<top;i++) System.out.println(no[i]); }
} class StackTest { public static void main(String arg[]) throws IOException { Stack
s=new Stack(); s.push(11); s.push(12); s.push(13); s.push(14); s.push(15);
s.push(16); s.print(); System.out.println("Pop ival="+s.pop()); s.print();
System.out.println("Pop ival="+s.pop()); s.print(); } } Output: Compilation:
Week:5-B
AIM: write a java program to convert infix expression to postfix expression forms.
File name: Edit intopost.java Source code: //import io package// import
java.io.*; class intopost { int top,j,i; String str; char t,postfix[],s[]; public intopost()
{ top=-1;i=0;j=0; postfix=new char[30]; s=new char[30]; } public void push(char t)
top++; s[top]=t; } public char pop()
{ char t; t=s[top]; top--; return t; } public void check() {
while(priority(t)<=priority(s[top])) postfix[j++]=pop(); } int priority(char t) {
if(t=='^') return 4; else if(t=='*') return 3; else if(t=='/') return 2;
else if(t=='+' || t=='-') return 1; else return 0; } public void convert(String str) {
Push(‘#’) while(i<str.length()) { t=str.charAt(i); if( (t>='a' && t<='z') || (t>='A' &&
t<='Z')) postfix[j++]=t; else { if(t=='+' || t=='-' || t=='*' || t=='/' || t=='(' || t==')' ||
t=='^') { switch(t) { case '+':
case '-': check(); push(t); break; case '*': case '/': check(); push(t); break; case '(':
push(t); break; case '^': check(); push(t); break; case ')': do { t=pop();
postfix[j++]=t;
}while(t!='('); j--; break;}}}
i++; } while(s[top]!='#') postfix[j++]=pop(); postfix[j]='\0';
System.out.println(postfix); } public static void main(String args[]) throws
IOException { String str; DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter a string?"); str=in.readLine(); (new
intopost()).convert(str); } }
Week:5-C AIM: write a java program to evaluate a postfix expression. File name:
Edit pfexevl.java Source code: //import io package// import java.io.*; /import
lang package// import java.lang.Math; class pfixevl { int top,j,i; String str; char
t,postfix[]; int s[]; DataInputStream in; public pfixevl() {
top=-1;i=0; postfix=new char[30]; s=new int[30]; in=new
DataInputStream(System.in); } public void push(int val) { top++; s[top]=val; }
public int pop() { int val; val=s[top]; top--; return val; } public void evaluate(String
str) throws IOException { int op1,op2,value=0; while(i<str.length()) {
t=str.charAt(i); if( (t>='a' && t<='z') || (t>='A' && t<='Z')) { System.out.print("Enter
value for '"+t+"' ?"); value=Integer.parseInt(in.readLine()); push(value); } else {
switch(t) { case '+': op2=pop(); op1=pop(); value=op1+op2; push(value); break;
case '-': op2=pop(); op1=pop(); value=op1-op2; push(value);
break; case '*': op2=pop(); op1=pop(); value=op1*op2; push(value); break; case
'/': op2=pop(); op1=pop(); value=op1*op2; push(value); break; case '^':
op2=pop(); op1=pop(); value=(int)Math.pow((float)op1,(float)op2); push(value);
break; } } i++;
} System.out.println("postfix evaluated val = "+value); } public static void
main(String args[]) throws IOException { String str; DataInputStream in=new
DataInputStream(System.in); System.out.print("Enter a string?");
str=in.readLine(); (new pfixevl()).evaluate(str); } }
Week:6-A Aim: write a java program to develop an applet that display simple
message. File name:
Applt.java Source code: import java.awt.*; import java.applet.*; public class applt
extends Applet { public void init() { resize(250,250); } public void paint(Graphics g)
{ Font myfont=new Font("Times new roman",Font.BOLD + Font.ITALIC,25);
g.setFont(myfont); g.drawRect(100,100,300,450); g.setColor(Color.orange);
g.fillRect(100,100,30,50); g.setColor(Color.red); g.drawString("hello
world",120,120); g.drawRect(100,100,300,450); g.setColor(Color.green);
g.fillRect(150,150,30,50); } } /* <applet code=applt.class height=300 width=400>
</applet> */
Week:6-B
AIM:Develop an Applet that receives an integer in one text field and
computes its factorial value and returans it in another text field,when the
button named compute is clicked. File name: edit appltfact.java Source code:
\\import java packages\\ import java.applet.*; import java.awt.*; import
java.awt.event.*; class actlstn implements ActionListener { public void
actionPerformed(ActionEvent e) { int ctr=1,no=0,fact=1; Button bt;
bt=(Button)e.getSource(); if((bt.getLabel()).equals("compute")) {
no=Integer.parseInt(appltfact.t1.getText()); while(ctr<=no)
{
fact*=ctr; ctr++; } appltfact.t2.setText(String.valueOf(fact)); }
System.out.println("...."); } } public class appltfact extends Applet { static TextField
t1,t2; Label l1,l2; Button b; public void init() { l1=new Label("enter an integer.");
l2=new Label("fatorial val:") t1=new TextField(); t2=new TextField(" "); b=new
Button("compute"); add(l1); add(t1);
add(l2); add(t2); b.addActionListener(new actlsn()); add(b); setSize(300,400);
setVisible(true); } public void paint(Graphics g) { showStatus("computing
Factorial value..."); } }
\\applet code\\ /* <applet code=appltfact.class height=300 width=500 >
</applet> */
Week:7 AIM:Write a java program that works as a simple calculator use a
grid layput to arrange for the digits and for +,-,*,/,% operations.Adda text
field to display the resut. File name: Edit appltcal.java Source code:
\\importing java packages\\ import java.applet.*; import java.awt.*; import
java.awt.event.*; //event listener interface for event handling class actlstn
implements ActionListener { public void actionPerformed(ActionEvent e) { int
no=0,val,prev; String txt;
Button bt;
bt=(Button)e.getSource(); txt=bt.getLabel(); if(txt.equals("C")) {
appltcal.t.setText(""); } else { if(txt.equals("+")) { if(appltcal.sta==0) {
appltcal.pval=Integer.parseInt(appltcal.t.getText()); appltcal.t.setText("");
appltcal.sta=1; } else { no=appltcal.pval;
no+=Integer.parseInt(appltcal.t.getText());
appltcal.t.setText(String.valueOf(no)); appltcal.sta=0; } } if(txt.equals("-")) {
if(appltcal.sta==0) { appltcal.pval=Integer.parseInt(appltcal.t.getText());
appltcal.t.setText(""); appltcal.sta=1; } else { no=appltcal.pval; no=Integer.parseInt(appltcal.t.getText()); appltcal.t.setText(String.valueOf(no));
appltcal.sta=0; } } if(txt.equals("*")) {
if(appltcal.sta==0) { appltcal.pval=Integer.parseInt(appltcal.t.getText());
appltcal.t.setText(""); appltcal.sta=1; } else { no=appltcal.pval;
no*=Integer.parseInt(appltcal.t.getText()); appltcal.t.setText(String.valueOf(no));
appltcal.sta=0; } }
if(txt.equals("/"))
{ if(appltcal.sta==0) { appltcal.pval=Integer.parseInt(appltcal.t.getText());
appltcal.t.setText(""); appltcal.sta=1; } else { no=appltcal.pval;
no/=Integer.parseInt(appltcal.t.getText()); appltcal.t.setText(String.valueOf(no));
appltcal.sta=0; } } if(txt.equals("%")) { if(appltcal.sta==0) {
appltcal.pval=Integer.parseInt(appltcal.t.getText()); appltcal.t.setText("");
appltcal.sta=1;
} else { no=appltcal.pval; no%=Integer.parseInt(appltcal.t.getText());
appltcal.t.setText(String.valueOf(no)); appltcal.sta=0; } } } } } public class appltcal
extends Applet { static int sta,pval; static TextField t; Button a,m,d,s,r,b; Panel p;
public void init()
{ t=new TextField("000000"); a=new Button("+"); s=new Button("-"); d=new
Button("/"); m=new Button("*"); r=new Button("%"); b=new Button("C");
//adding listener actlstn lstn=new actlstn(); a.addActionListener(lstn);
s.addActionListener(lstn); d.addActionListener(lstn); m.addActionListener(lstn);
r.addActionListener(lstn); b.addActionListener(lstn); //setting panel and layout
p=new Panel(); p.setLayout(new GridLayout(3,2)); p.add(t); p.add(a); p.add(s);
p.add(d); p.add(m); p.add(r); p.add(b); //adding pane add(p); setSize(300,400);
setVisible(true); } public void paint(Graphics g) { showStatus("Calculator..."); } }
//applet code // /*
<applet code=appltcal.class height=300 width=400> </applet> */
Week:8-A AIM:Write a java program for handling mouse events [whenever user
moves the mouse it had to display the xy coordinates on the canvas(graphics]
File name:
edit appltmouse.java Source code: import java.applet.; import java.awt.Graphics;
import java.awt.TextField; import java.awt.event.MouseMotionListener; import
java.awt.event.MouseEvent; import java.awt.Panel; public class appltmouse1
extends Applet implements MouseMotionListener { static TextField t; int x,y;
public void mouseDragged(MouseEvent m) { } public void
mouseMoved(MouseEvent m) { x=m.getX(); y=m.getY();
appltmouse.t.setText(String.valueOf(x)+" , "+String.valueOf(y)); repaint();
} public void init() { t=new TextField("........"); Panel p=new Panel(); p.add(t);
add(p); //mouse event deligation addMouseMotionListener(this); setSize(300,400);
setVisible(true); } public void paint(Graphics g) { g.drawRect(20,20,100,200);
g.drawString(t.getText(),x,y); } }
//applet code///
/* <applet code=appltmouse1.class height=300 width=400 >
</applet> */
9)a)
AIM:Write a java program that create 3 threads that the 1st thread to display
GOOD MORNING for every 1second,2nd thread to display HELLO for every
2seconds and the 3rd thread to display WELCOME for every 3 seconds. File
name:edit multhread.java Source code: import java.io.*; import java.lang.*; class
threada extends Thread { public void run() { for(; ;) { try {
System.out.println("GOOD MORNING"); sleep(1000); } catch(Exception e)
{
System.out.println(e.toString()); } } } } class threadb extends Thread { public void
run() { for(; ;) { try { System.out.println("HELLO"); sleep(2000); }
catch(Exception e) { System.out.println(e.toString()); } } } } class threadc extends
Thread { public void run() { for(; ;) { try { System.out.println("WELCOME");
sleep(3000); } catch(Exception e) { System.out.println(e.toString()); } } } } class
multhreadss { public static void main(String arg[]) { //creating new thread threada
t1=new threada(); threadb t2=new threadb(); threadc t3=new threadc(); //staring
threads t1.start(); t2.start(); t3.start(); } }
Output: Compilation: D:/csejava>javac multhreadss.java Interpretation:
D:\csejava>java multhreadss
Week:9-B AIM: write a java program that implements producer,consumer
problem using the concept of inter threacommunication. File name: Edit
producerconsumer.java Source code:
\\import io package\\ import java.io.*; class Consumer extends Thread { private
CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c,int
number) { cubbyhole=c; this.number=number; } public void run() { int value=0;
for(int i=0;i<10;i++) { value=cubbyhole.get(); System.out.println("Consumer’
#’this.number+got+value); } } } class Producer extends Thread { private
CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int
number) { cubbyhole=c; this.number=number; } public void run() { for(int
i=10;i<20;i++) { cubbyhole.put(i); try { sleep(100); } catch(InterruptedException
e) { e.printStackTrace(); } System.out.println("Consumer #"+this.number+"put:"
+i); } } } class CubbyHole { private int contents; private boolean available=false;
public synchronized int get() while(available==false) { try { wait(); }
Catch(exception e) { e.printStackTrace(); } } available=false; notifyAll(); return
contents; } public synchronized void put(int value) { while(available==true) { try {
wait(); } catch (InterruptedException e) { e.printStackTrace(); } } available=true;
contents=value; notifyAll(); } } public class ProducerConsumer { public static
void main(String arg[]) { CubbyHole c=new CubbyHole(); Producer p1= new
Producer(c,2); Consumer c1=new Consumer(c,1);
p1.start(); c1.start(); } } Output: Compilation: D:\cse>javac
producerconsumer.java Interpretation: D:\cse>java producerconsumer
Week:10- AIM:Program to create an interface to perform division operations
when user enters the two integers.The division of two values must displayed in
tth ethird text box when user clicks the CAL button.if num1 & num2 are not
integers then the program to throw NumberFormatException,when num1
divide with 0 it has to throw ArithematicException in exception Message
label. File name: framediv.java Source code: import java.io.*; import
java.awt.*; import java.awt.event.*; import javax.swing.*; class framediv extends
JFrame implements ActionListener JPanel p; JTextField t1,t2,t3; JButton b; JLabel
msg; public void actionPerformed(ActionEvent e) { int n1,n2,n3; JButton bt;
bt=(JButton)e.getSource(); if(bt.getLabel().equals("Cal")) { try {
n1=Integer.parseInt(t1.getText()); n2=Integer.parseInt(t2.getText()); n3=n1/n2;
t3.setText(String.valueOf(n3)); msg.setText("Calculation performed......"); }
catch(NumberFormatException ex) { msg.setText("Wrong Data Values are
enetered..."); } catch(ArithmeticException ex) { msg.setText("Zero divide canot
possible"); } } } public framediv() { setTitle("Frame for division.."); p=new
JPanel(); t1=new JTextField("10000"); t2=new JTextField("1000"); t3=new
JTextField("Result Here"); b=new JButton("Cal"); //adding action listener
b.addActionListener(this); p.add(t1); p.add(new JLabel(" / ")); p.add(t2);
p.add(new JLabel(" = ")); p.add(t3); p.add(b); msg=new JLabel("Click Cal Button
to perform cal..."); p.add(msg); add(p); setSize(300,400); setVisible(true); } public
static void main(String args[]) { new framediv(); } }
Output: Compilation: D:\csejava>javac
Interpretation: D:\csejava>appletviewer framediv.java
Week-11-a
AIM: write a java program that simulates trafficlight the program let user
select one of three lights ,thread yellowor green .when a radio button is select
the light is turn ed one light can be on at atime. No lights is on when the
program starts. File name: Edit framelights.java So urce code:
\\import java packages\\ import java.awt.*; import java.awt.event.*; class
framelights implements ItemListener { Frame f; Label l; Checkbox b1,b2,b3;
CheckboxGroup g; Panel p; public void itemStateChanged(ItemEvent e) {
Checkbox c=(Checkbox)e.getSource();
if(c.getLabel().equals("Red")) { l.setText("Red color..."); } else
if(c.getLabel().equals("Yellow")) { l.setText("Yellow color..."); } else
if(c.getLabel().equals("Green")) { l.setText("Green color..."); } } public
framelights() { f=new Frame("Frame with Lights"); l=new Label("COLOR
BOX....."); g=new CheckboxGroup(); b1=new Checkbox("Red",g,false) b2=new
Checkbox("Yellow",g,false); b3=new Checkbox("Green",g,false);
b1.addItemListener(this); b2.addItemListener(this); b3.addItemListener(this);
p=new Panel(); p.add(l); p.add(b1); p.add(b2); p.add(b3); f.add(p);
f.setSize(300,400); f.setVisible(true); } public static void main(String[] args) { new
framelights(); } }
Output: Compilation: D:/cse>javac framelights.java Interpretation: D:/cse>java
framelights
Week:11-b AIM:Write a java program to draw a line,ellipse and rectangle.
Filename:edit appltdraw.java Source code:
\\import java packages\\ import java.awt.*; import java.applet.*; public class
appltdraw extends java.applet.Applet { public void init() { resize(250,250); }
public void paint(Graphics g) { //orange rect
g.drawRect(100,100,300,450); g.setColor(Color.orange);
g.fillRect(100,100,30,50); //red line g.setColor(Color.red);
g.drawLine(0,0,120,120); //blue rect g.setColor(Color.blue);
g.drawRect(100,100,30,50); g.setColor(Color.green); g.fillRect(150,150,30,50);
//gray oval g.setColor(Color.gray); g.drawOval(0,0,50,100); } }
\\applet code\\ /* <applet code=appltdraw.class height=300 width=400> </applet>
*/
Out put: Compilation: E:\ADITYA\csejava>javac appltdraw.java
Interpretation: E:\ADITYA\csejava>appletviewer appltdraw.java
Week-12
a) Write a java program to create an abstract class named Shape that contains an empty method named
numberOfSides ( ).Provide three classes named Trapezoid, Triangle and Hexagon such that each one of the
classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that
shows the number of sides in the given geometrical figures.
import javax.swing.*;
abstract class Shape
{
public abstract void numberOfSides();
}
class Trapezoid extends Shape
{
public void numberOfSides()
{
JOptionPane.showMessageDialog(null,"TRAPEZOID -- Number of sides in trapezoid is 4 (Of which two
are parallel and with no angles)");
}
}
class Triangle extends Shape
{
public void numberOfSides()
{
JOptionPane.showMessageDialog(null,"TRIANGLE -- Number of sides in Triangle is 3 ");
}
}
class Hexagon extends Shape
{
public void numberOfSides()
{
JOptionPane.showMessageDialog(null,"HEXAGON -- Number of sides in Hexagon is 6 ");
}
}
class ShapeDemo
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,"Some of the Geometrical figures are as follows " );
Trapezoid t=new Trapezoid();
Triangle tg=new Triangle();
Hexagon h=new Hexagon();
t.numberOfSides();
tg.numberOfSides();
h.numberOfSides();
}
}
b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the
remaining lines correspond to rows in the table. The elements are 43eparated by commas. Write a java
program to display the table using Jtable component.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Table1 extends JFrame
{
int i=0;
int j=0,k=0;
Object data[][]=new Object[5][4];
Object list[][]=new Object[5][4];
JButton save;
JTable table1;
FileInputStream fis;
DataInputStream dis;
public Table1()
{
String d= " ";
Container con=getContentPane();
con.setLayout(new BorderLayout());
final String[] colHeads={"Name","Roll Number","Department","Percentage"};
try
{
String s=JOptionPane.showInputDialog("Enter the File name present in the current directory");
FileInputStream fis=new FileInputStream(s);
DataInputStream dis = new DataInputStream(fis);
while ((d=dis.readLine())!=null)
{
StringTokenizer st1=new StringTokenizer(d,",");
while (st1.hasMoreTokens())
{
for (j=0;j<4;j++)
{
data[i][j]=st1.nextToken();
System.out.println(data[i][j]);
}
i++;
}
System.out.println("______________");
}
}
catch (Exception e)
{
System.out.println("Eception raised" +e.toString());
}
table1=new JTable(data,colHeads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll=new JScrollPane(table1,v,h);
con.add(scroll,BorderLayout.CENTER);
}
public static void main(String args[])
{
Table1 t=new Table1();
t.setBackground(Color.green);
t.setTitle("Display Data");
t.setSize(500,300);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Related documents