object oriented programming lab - sree vahini

46
Object Oriented Programming Lab OOPs through Java JNTUH B.Tech CSE II-II Sem 2013- 2014 P.Srinivas, Assistant Profess in CSE Malla Reddy Institute of Technology (MRIT) 2013-2014 www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net www.jntuworld.com || www.jwjobs.net

Upload: others

Post on 10-May-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab OOPs through Java JNTUH B.Tech CSE II-II Sem

2013-2014

P.Srinivas, Assistant Profess in CSE Malla Reddy Institute of Technology (MRIT)

2013-2014

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 2: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 1

SNO EXP NO EXPERIMENT NAME PAGE NO

1

Week – 1

a) Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a ,b, c and use the quadratic formula. If the discriminate b2-4ac is negative, display a message stating that there are no real solutions.

3

2 b) The Fibonacci sequence is defined by the following rules: The first two values in the sequence are 1 and 1. Every subsequent values is the sum of the two values preceding it. Write a java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence.

4

3

Week – 2

a) Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer.

6

4 b) Write a Java program to Multiply two given matrices. 7 5 c) Write a Java program that reads a line of integers and then

displays each integer, and the sum of all the integers( Use String Tokenizer class of java.util)

10

6

Week – 3

a) Write a Java program that checks whether a given string is a palindrome or not. Ex MADAM is a palindrome

11

7 b) Write a Java Progarm for sorting a given list of names in ascending order.

12

8 c) Write a Java Program to make frequency count of words in a given text.

13

9

Week - 4

a) Write a Java Program that reads a file name from the user, then display information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes.

14

10 b) Write a Java program that reads a file and displays the file on the screen, with a line number before each line.

15

11 c) Write a Java program that displays the number of characters, lines and words in a text file.

16

12

Week – 5

Write a Java program that: i) Implement Stack ADT

17

13 ii) Converts Infix equation into Postfix form 20 14 ii) Evaluate the Postfix expression 23 15

Week – 6

a) Develop an applet that displays a simple message. 24 16 b) Develop an applet that receives an integer in one text field and

compute its factorial value in another text field, when the button named ‘Compute” is clicked.

25

17 Week - 7 Write a Java program that works as a simple calculator. Use a grid Layout to arrange buttons for the digits and for the +, -, *, / operations. Add a text field to display the results.

26

18 Week – 8 Write a Java program for handling mouse and key events 29 19

Week – 9

a) Write a Java program that creates three threads. First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds.

31

20 b) Write a Java program that correctly implements producer 33

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 3: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 2

consumer problem using the concept of inter thread communication

21 Week – 10 Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception Display the exception in a message dialog box.

35

22

Week – 11

a) Write a java program that simulates a traffic light. The program lets the user select one of three lights: red, yellow or green. When a radio button is selected, the light is turned on, and only one light can be on at a time. No light is on when the program starts.

38

23 b) Write a Java program that allows the user to draw lines, rectangle and ovals.

40

24

Week – 12

a) Write a java program to create an abstract class named Shape that contain 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 class contains only the method numberOfSides() that shows the number of sides in the given geometrical figures.

41

25 b) Suppose that a table 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 separated by commas. Write a java program to display the table using JTable component.

44

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 4: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 3

Week 1:

a) Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a ,b, c and use the quadratic formula. If the discriminate b2-4ac is negative, display a message stating that there are no real solutions. import java.io.*; import java.math.*; class Quad { public static void main(String[] args) throws Exception { int a,b,c,d; float r1,r2; System.out.println("Enter a , b & c values"); DataInputStream dis=new DataInputStream(System.in); a=Integer.parseInt(dis.readLine()); b=Integer.parseInt(dis.readLine()); c=Integer.parseInt(dis.readLine()); d=(b*b)-(4*a*c); if (d==0) { r1=r2=(float)(-b/(2*a)); System.out.println("The roots are equal\nr1="+r1+" and r2="+r2); } else if(d>0) { r1=(float)(-b+Math.sqrt(d))/(2*a); r2=(float)(-b-Math.sqrt(d))/(2*a); System.out.println("The roots are real & distinct\n r1="+r1+" and r2="+r2); } else if(d<0) { r1=(float)(-b/(2*a)); r2=(float)(Math.sqrt(-d)/(2*a)); System.out.println("The roots are complex & imaginary\nr1="+r1+"+i"+r2+"\nr2="+r1+"-i"+r2); } } } Output: D:\Lab>javac Quad.java D:\Lab>java Quad Enter a , b & c values 3 2 1 The roots are complex & imaginary r1=0.0+i0.47140452 r2=0.0-i0.47140452

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 5: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 4

Week b)

The Fibonacci sequence is defined by the following rules: The first two values in the sequence are 1 and 1. Every subsequent values is the sum of the two values preceding it. Write a java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence.

import java.io.*; import java.math.*; class Fibonacci { int Fib(int n) { if(n==0) return 0; else if(n==1) return 1; else return Fib(n-1)+Fib(n-2); } } class Fibrec { public static void main(String[] args) throws Exception { int n; long r=0; System.out.println("Enter N value:"); DataInputStream dis=new DataInputStream(System.in); n=Integer.parseInt(dis.readLine()); Fibonacci f=new Fibonacci(); for(int i=1;i<=n; i++) { System.out.print(f.Fib(i)+"\t"); r=f.Fib(n); } System.out.println("\nThe "+n+" the value in the Fibonacci Series : "+r); } } OUTPUT:

D:\Lab>javac Fibrec.java D:\Lab>java Fibrec Enter N value: 10 1 1 2 3 5 8 13 21 34 55 The 10 the value in the Fibonacci Series : 55

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 6: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 5

import java.io.*; import java.math.*; class Fibonacci { int a=1,b=1,c; int Fib(int no) { for(int i=1;i<=no-2;i++) { c=a+b; System.out.print("\t"+c); a=b; b=c; } return c; } } class Fibnonrec { public static void main(String[] args) throws Exception { int n,r; System.out.println("Enter N value:"); DataInputStream dis=new DataInputStream(System.in); n=Integer.parseInt(dis.readLine()); Fibonacci f=new Fibonacci(); System.out.print(f.a+"\t"+f.b); r=f.Fib(n); System.out.println("\nThe "+n+" the value in the Fibonacci Series : "+r); } } OUTPUT: D:\Lab>javac Fibnonrec.java D:\Lab>java Fibnonrec Enter N value: 10 1 1 2 3 5 8 13 21 34 55 The 10 the value in the Fibonacci Series : 55

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 7: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 6

Week 2: a) Write a program that prompts the user for an integer and then prints out all prime

numbers up to that integer. import java.io.*; class Primenos { public static void main(String[] args) throws Exception { int n,fact; System.out.println("Enter the range of Prime No U want"); DataInputStream dis=new DataInputStream(System.in); n=Integer.parseInt(dis.readLine()); System.out.println("Prime No's from 1 to "+n+" is"); for(int i=1;i<=n;i++) { fact=1; for(int x=1;x<i;x++) if(i%x==0) fact++; if(fact==2) System.out.print(i+"\t"); } } } OUTPUT: D:\Lab>javac Primenos.java D:\Lab>java Primenos Enter the range of Prime No U want 100 Prime No's from 1 to 100 is 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 8: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 7

Week b) Write a Java program to Multiply two given matrices. import java.io.*; class Matrix { int a[][],b[][],c[][]; int i,j,k,m,n,p,q; DataInputStream dis=new DataInputStream(System.in); void readA() { try { System.out.println("Enter the Size of Matrix A (Rows and Columns) "); m=Integer.parseInt(dis.readLine()); n=Integer.parseInt(dis.readLine()); a=new int[m][n]; System.out.println("Enter the Matrix A values:"); for(i=0;i<m;i++) for(j=0;j<n;j++) a[i][j]=Integer.parseInt(dis.readLine()); } catch(Exception e){} } void readB() { try { System.out.println("Enter the Size of Matrix B (Rows and Columns) "); p=Integer.parseInt(dis.readLine()); q=Integer.parseInt(dis.readLine()); b=new int[p][q]; System.out.println("Enter the Matrix A values:"); for(i=0;i<p;i++) for(j=0;j<q;j++) b[i][j]=Integer.parseInt(dis.readLine()); }catch(Exception e){} } void printA() { System.out.println("Matrix A \n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { System.out.print(a[i][j]+"\t"); } System.out.println(" "); } } void printB() { System.out.println("Matrix B \n"); for(i=0;i<p;i++) { for(j=0;j<q;j++) { System.out.print(b[i][j]+"\t");

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 9: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 8

} System.out.println(" "); } } void mulAB() { c=new int[m][q]; for(i=0;i<m;i++) for(j=0;j<q;j++) { c[i][j]=0; for(k=0;k<p;k++) c[i][j]+=a[i][k]*b[k][j]; } } void printC() { System.out.println("Matrix Multiplication is \n"); for(i=0;i<m;i++) { for(j=0;j<q;j++) { System.out.print(c[i][j]+"\t"); } System.out.println(" "); } } } class MatrixMul { public static void main(String[] args) throws Exception { Matrix mat=new Matrix(); mat.readA(); mat.readB(); if(mat.n==mat.p)

{ mat.printA(); mat.printB(); mat.mulAB(); mat.printC();

} else System.out.println("Matrix Multiplication is Not Possible"); } } OUTPUT: D:\Lab>javac MatrixMul.java D:\Lab>java MatrixMul Enter the Size of Matrix A (Rows and Columns) 2 2 Enter the Matrix A values: 1 2 1 2

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 10: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 9

Enter the Size of Matrix B (Rows and Columns) 2 2 Enter the Matrix A values: 2 1 2 1 Matrix A 1 2 1 2 Matrix B 2 1 2 1 Matrix Multiplication is 6 3 6 3 D:\Lab>java MatrixMul Enter the Size of Matrix A (Rows and Columns) 2 3 Enter the Matrix A values: 2 3 2 3 2 1 Enter the Size of Matrix B (Rows and Columns) 2 3 Enter the Matrix A values: 2 2 2 2 2 2 Matrix Multiplication is Not Possible

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 11: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 10

Week c) Write a Java program that reads a line of integers and then displays each integer, and the sum of all the integers( Use String Tokenizer class of java.util) import java.io.*; import java.util.*; class StringToken { public static void main(String[] args) throws Exception { int i=0,sum=0; DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter the Line of Integer Separated by Space"); String str=dis.readLine(); int n=str.length(); int a[]=new int[n]; StringTokenizer st=new StringTokenizer(str); while(st.hasMoreTokens()) { a[i]=Integer.parseInt(st.nextToken()); System.out.println("a["+i+"]= "+a[i]); i++; } for(i=0;i<n;i++) sum+=a[i]; System.out.println("Sum is = "+sum); } } OUTPUT: D:\Lab>javac StringToken.java D:\Lab>java StringToken Enter the Line of Integer Separated by Space 1 2 3 4 5 a[0]= 1 a[1]= 2 a[2]= 3 a[3]= 4 a[4]= 5 Sum is = 15

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 12: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 11

Week 3: a) Write a Java program that checks whether a given string is a palindrome or not. Ex

MADAM is a palindrome import java.io.*; class Palindrome { public static void main(String[] args) throws Exception { String str1, str2; DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter a String"); str1=dis.readLine(); StringBuffer tmp=new StringBuffer(str1); tmp.reverse(); str2=new String(tmp); System.out.println("The String after Reverse is "+str2); if(str1.equals(str2)) System.out.println("The given String "+str1+" is palindrome"); else System.out.println("The given String "+str1+" is not palindrome"); } } OUTPUT: D:\Lab>javac Palindrome.java D:\Lab>java Palindrome Enter a String madam The String after Reverse is madam The given String madam is palindrome D:\Lab>java Palindrome Enter a String abcde The String after Reverse is edcba The given String abcde is not palindrome

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 13: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 12

b) Write a Java Progarm for sorting a given list of names in ascending order. import java.io.*; class SortingStr { public static void main(String[] args) throws Exception { int n,i,j; DataInputStream dis=new DataInputStream(System.in); System.out.println("Ente the number of Strings :"); n=Integer.parseInt(dis.readLine()); String str[]=new String[n]; for(i=0;i<n;i++) { System.out.println("Enter string "+(i+1)+" :"); str[i]=dis.readLine(); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if((str[i].compareTo(str[j]))>0) { String tmp=str[i]; str[i]=str[j]; str[j]=tmp; } } } System.out.println("The String after Sorting : "); for(i=0;i<n;i++) System.out.println(str[i]); } }

OUTPUT: D:\Lab>javac SortingStr.java D:\Lab>java SortingStr Ente the number of Strings : 5 Enter string 1 : rama Enter string 2 : krishna Enter string 3 : raju Enter string 4 : abc Enter string 5 : sai The String after Sorting : abc krishna raju rama sai

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 14: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 13

c) Write a Java Program to make frequency count of words in a given text. import java.io.*; import java.util.*; class Freq { public static void main(String[] args) throws Exception { DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter a String :"); String s=dis.readLine(); StringTokenizer st=new StringTokenizer(s); int count=1,i=0; int size=st.countTokens(); String words[]=new String[size]; while(st.hasMoreTokens()) { words[i]=st.nextToken(); i++; } for(i=0;i<size;i++) { count=1; for(int j=i+1;j<size;j++) { if(words[i].equals(words[j])) { count++; move(words,j,size); size--; j--; } } System.out.println(words[i]+" occurs "+count+" no of times"); } } static void move(String a[],int i,int size) { while(i<size) { if(i==size-1) a[i]=null; else a[i]=a[i+1]; i++; } } } OUTPUT: D:\Lab>javac Freq.java D:\Lab>java Freq Enter a String : jai bolo hanuman ki jai jai occurs 2 no of times bolo occurs 1 no of times hanuman occurs 1 no of times ki occurs 1 no of times

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 15: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 14

Week 4: a) Write a Java Program that reads a file name from the user, then display information about

whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes.

import java.io.*; class FileEx { public static void main(String[] args) { DataInputStream dis=new DataInputStream(System.in); File f=new File("D:/Lab/abc/abc.txt"); System.out.println("File Name = "+f.getName()); System.out.println("File Path = " +f.getPath()); System.out.println("File parent = "+f.getParent()); System.out.println(f.isFile()?" is a File":"not a file"); System.out.println(f.isDirectory()?"it is a directory":"not a directory"); System.out.println(f.canRead()?" it is readable":"it is not readable"); System.out.println(f.canWrite()?"it is writable":"it is not writable"); System.out.println("length of file is"+f.length()); } } OUTPUT: D:\Lab>javac FileEx.java D:\Lab>java FileEx File Name = abc.txt File Path = D:\Lab\abc\abc.txt File parent = D:\Lab\abc is a File not a directory it is readable it is not writable length of file is68

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 16: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 15

Week b) Write a Java program that reads a file and displays the file on the screen, with a line number before each line.

import java.io.*; class FileRead { public static void main(String[] args) throws Exception { File f=new File("FileRead.java"); FileReader fr=new FileReader(f); BufferedReader br=new BufferedReader(fr); String str=br.readLine(); int i=1; while((str=br.readLine())!=null) { System.out.println(i++ +" "+str); } fr.close(); } } OUTPUT: D:\Lab>javac FileRead.java D:\Lab>java FileRead 1 class FileRead 2 { 3 public static void main(String[] args) throws Exception 4 { 5 File f=new File("FileRead.java"); 6 FileReader fr=new FileReader(f); 7 BufferedReader br=new BufferedReader(fr); 8 String str=br.readLine(); 9 int i=1; 10 while((str=br.readLine())!=null) 11 { 12 System.out.println(i++ +" "+str); 13 } 14 fr.close(); 15 } 16 }

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 17: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 16

Week c) Write a Java program that displays the number of characters, lines and words in a text file.

import java.io.*; import java.util.*; class FileCount { public static void main(String[] args) throws Exception { String fname; System.out.println("Enter a filename:"); DataInputStream dis=new DataInputStream(System.in); fname=dis.readLine(); FileReader f=new FileReader(fname); BufferedReader br=new BufferedReader(f); String str; int words=0,lines=0,chars=0; while((str=br.readLine())!=null) { StringTokenizer st=new StringTokenizer(str); lines++; words+=st.countTokens(); int i=0,n; n=str.length(); for(i=0;i<n;i++) { char ch=str.charAt(i); if(ch!=' ') chars++; } } System.out.println("the number of lines in the file are = "+lines); System.out.println("the number of words in the file are = "+words); System.out.println("the number of characters in the file are = "+chars); } } OUTPUT: D:\Lab>javac FileCount.java D:\Lab>java FileCount Enter a filename: FileCount.java the number of lines in the file are = 34 the number of words in the file are = 85 the number of characters in the file are = 749

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 18: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 17

Week 5: a) Write a Java program that: i) Implement Stack ADT

import java.io.*; class StackDemo { public static void main(String[] args) throws Exception { Stack st=new Stack(); DataInputStream dis=new DataInputStream(System.in); while(true) { System.out.println("MENU\n1.PUSH\n2.POP\n3.Display\n4.Exit"); System.out.println("Enter Ur Choice:"); int ch=Integer.parseInt(dis.readLine()); switch(ch) { case 1: System.out.println("Enter element to Push into Stack:"); int a=Integer.parseInt(dis.readLine()); st.push(a);break; case 2: st.pop();break; case 3:st.display();break; case 4:System.exit(0);break; } } } } interface StackADT { void push(Object o); void pop(); void display(); } class Stack implements StackADT { Object o[]; int top=-1; int size=10; Stack() { o=new Object[10]; } Stack(int size) { o=new Object[size]; } public void push(Object obj) { if (size==o.length-1) System.out.println("Stack is OverFlow"); else o[++top]=obj; } public void pop() {

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 19: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 18

if(top==-1) System.out.println("Stack is empty"); else { System.out.println("Element "+o[top]+"is deleted from stack"); top=top-1; } } public void display() { if(top==-1) System.out.println("Stack is empty"); else System.out.println("Elements in the Stack are:"); for(int i=0;i<=top;i++) System.out.println(o[i]); } } OUTPUT: D:\Lab>javac StackDemo.java D:\Lab>java StackDemo MENU 1.PUSH 2.POP 3.Display 4.Exit Enter Ur Choice: 3 Stack is empty MENU 1.PUSH 2.POP 3.Display 4.Exit Enter Ur Choice: 1 Enter element to Push into Stack: 10 MENU 1.PUSH 2.POP 3.Display 4.Exit Enter Ur Choice: 1 Enter element to Push into Stack: 20 MENU 1.PUSH 2.POP 3.Display 4.Exit

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 20: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 19

Enter Ur Choice: 2 Element 20is deleted from stack MENU 1.PUSH 2.POP 3.Display 4.Exit Enter Ur Choice: 2 Element 10is deleted from stack MENU 1.PUSH 2.POP 3.Display 4.Exit Enter Ur Choice: 2 Stack is empty MENU 1.PUSH 2.POP 3.Display 4.Exit Enter Ur Choice: 4

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 21: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 20

ii) Converts Infix equation into Postfix form

import java.io.*; import java.util.*; class charstack { int top,size; char stack[],ele; charstack(int n) { size=n; top=-1; stack=new char[n]; } void push(char x) { ele=x; if(!isfull()) { stack[++top]=ele; } else System.out.println("stack is full"); } char pop() { if(!isempty()) { return stack[top--]; } else { System.out.println("stack is empty"); return 'a'; } } boolean isempty() { if(top==-1) return true; else return false; } boolean isfull() { if(top>size) return true; else return false; } void display() { if(!isempty()) System.out.println("="+stack[top]); else System.out.println("stack is empty");

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 22: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 21

} char peek() { return stack[top]; } } class InfixToPostfix { charstack cs; char pf[]; InfixToPostfix() { cs=new charstack(50); pf=new char[50]; } boolean iop(char op) { if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'||op=='^'||op=='%') return true; else return false; } int prec(char op) { if(op=='+'||op=='-') return 1; else if(op=='/'||op=='*') return 2; else if(op=='%'||op=='^') return 3; return 0; } void infixtop(String infix) { char isym; int j=0; char ir[]=infix.toCharArray(); for(int i=0;i<ir.length;i++) { isym=ir[i]; if(!iop(isym)) { pf[j]=isym; j++; } else { if(isym=='('||cs.isempty()) cs.push(isym); else if(isym==')') { while(cs.peek()!='(') { pf[j]=cs.pop(); j++; }

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 23: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 22

char v=cs.pop(); } else if(cs.isempty()) cs.push(isym); else if(cs.isempty()||cs.peek()=='('||(prec(cs.peek())<prec(isym))) cs.push(isym); else { while((!cs.isempty())&&(cs.peek()!='(')&&prec(cs.peek())>=prec(isym)) { pf[j]=cs.pop(); j++; } cs.push(isym); } } } while(!cs.isempty()) { pf[j]=cs.pop(); j++; } } void display1() { for(int i=0;i<pf.length-1;i++) System.out.print(pf[i]); } public static void main(String args[])throws Exception { InfixToPostfix ob=new InfixToPostfix(); Scanner r=new Scanner(System.in); System.out.println("enter any equation:"); String s=r.nextLine(); ob.infixtop(s); ob.display1(); } } OUTPUT: D:\Lab>javac InfixToPostfix.java D:\Lab>java InfixToPostfix enter any equation: a+b*c-d abc*+d-

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 24: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 23

iii) Evaluate the Postfix expression

import java.io.*; import java.util.*; class PostEval { public static void main(String[] args) throws Exception { String postfixexp; DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter the Postfix Expression to be evaluated:"); postfixexp=dis.readLine(); java.util.Stack<Integer> st=new java.util.Stack<Integer>(); int ans=0; for(int i=0;i<postfixexp.length();i++) { char ch=postfixexp.charAt(i); if(ch>'0'&&ch<='9') { String str=(new Character(ch)).toString(); st.push(Integer.parseInt(str)); } else { int n2=st.pop().intValue(); int n1=st.pop().intValue(); switch(ch) { case '+': ans=n1+n2;break; case '-':ans=n1-n2;break; case '*':ans=n1*n2;break; case '/':ans=n1/n2;break; default: System.out.println("Invalid operator");break; } st.push(new Integer(ans)); } } System.out.println("Value of the Postfix expression is "+st.pop()); } } OUTPUT: D:\Lab>javac PostEval.java D:\Lab>java PostEval Enter the Postfix Expression to be evaluated: 123*+4- Value of the Postfix expression is 3

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 25: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 24

Week 6 : a ) Develop an applet that displays a simple message.

import java.awt.*; import java.applet.*; /*<applet code="MyApplet" width=500 height=200> </applet>*/ public class MyApplet extends Applet { String str="Welcome to MallaReddy Institute of Tech."; public void init() { setBackground(Color.orange); setForeground(Color.blue); Font f=new Font("Dialog",Font.BOLD,25); setFont(f); } public void paint(Graphics g) { g.drawString(str,10,100); } } OUTPUT: D:\Lab>javac MyApplet.java D:\Lab>appletviewer MyApplet.java (OR) D:\Lab>appletviewer sample.html

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 26: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 25

b) Develop an applet that receives an integer in one text field and compute its factorial value in another text field, when the button named ‘Compute” is clicked.

import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code="FactApplet" width=500 height=250> </applet>*/ public class FactApplet extends Applet implements ActionListener { TextField num, res; Button b1; public void init() { setLayout(null); Label l1=new Label("Enter the Number:"); l1.setBounds(10,50,100,30); num=new TextField(); num.setBounds(200,50,100,30); Label l2=new Label("The Factorial is :"); l2.setBounds(10,100,100,40); res=new TextField(); res.setBounds(200,100,100,40); b1=new Button("Compute"); b1.setBounds(200,150,70,40); add(l1); add(l2); add(num); add(res); add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if((ae.getSource())==b1) { int n=Integer.parseInt(num.getText()); int i,fact=1; for(i=1;i<=n;i++) fact=fact*i; res.setText(" "+fact); } } } OUTPUT: D:\Lab>javac FactApplet.java D:\Lab>appletviewer FactApplet.java

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 27: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 26

Week 7: Write a Java program that works as a simple calculator. Use a grid Layout to arrange buttons for the digits and for the +, -, *, / operations. Add a text field to display the results.

import java.awt.*; import java.awt.event.*; class Calculator extends Frame implements ActionListener { TextField f; boolean reset=false,opset=false; String s=" "; int n1=0,n2=0,res=0; char op=' '; Calculator() { setVisible(true); setTitle("CALCULATOR"); setSize(600,600); setLayout(null); Button b[]=new Button[16]; Panel p=new Panel(); p.setLayout(new GridLayout(4,4)) ; p.setBounds(200,200,200,200); b[0]=new Button("0"); for(int i=1;i<10;i++) { p.add(b[i]=new Button(i+" ")); } b[10]=new Button("+"); b[11]=new Button("-"); b[12]=new Button("*"); b[13]=new Button("/"); b[14]=new Button("="); b[15]=new Button("C"); p.add(b[0]); p.add(b[10]); p.add(b[11]); p.add(b[12]); p.add(b[13]); p.add(b[14]); p.add(b[15]); f=new TextField("0"); f.setBounds(200,160,200,40); add(f); add(p); for(int j=0;j<16;j++) { b[j].addActionListener(this); } } public static void main(String args[]) { new Calculator(); } public void actionPerformed(ActionEvent e) { String s=" ";

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 28: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 27

char ch=(e.getActionCommand().charAt(0)); switch(ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (!reset) { if((s=f.getText()).equals("0")) { f.setText(ch+""); reset=false; } else { s=f.getText(); f.setText(s+ch); } } else { f.setText(ch+""); reset=false; } break; case '+': case '-': case '*': case '/': if (!opset) { n1=Integer.parseInt(f.getText()); op=ch; opset=true; f.setText("0"); break; } else { n2=Integer.parseInt(f.getText()); if(op=='+') res=n1+n2; if(op=='-') res=n1-n2; if(op=='*') res=n1*n2; if(op=='/') res=n1/n2; f.setText(res+""); n1=res; op=ch; reset=true; break;

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 29: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 28

} case '=': n2=Integer.parseInt(f.getText());

if(op=='+') res=n1+n2; if(op=='-') res=n1-n2; if(op=='*') res=n1*n2; if(op=='/') res=n1/n2; f.setText(res+""); reset=true; opset=false; break; case 'C': n1=n2=res=0; op=' '; f.setText("0"); reset=false; opset=false; break; } } } OUTPUT: D:\Lab>javac Calculator.java D:\Lab>java Calculator

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 30: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 29

Week 8 : Write a Java program for handling mouse and key events import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; /*<applet code="MouseDemo" width=400 height=400> </applet>*/ public class MouseDemo extends Applet implements MouseListener,MouseMotionListener { String msg=" "; int mx=0,my=0; public void init() { setBackground(Color.white); setForeground(Color.red); addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me){ mx=0;my=10; msg="mouse clicked"; repaint(); } public void mouseEntered(MouseEvent me){ mx=0;my=10; msg="mouse entered"; repaint(); } public void mouseExited(MouseEvent me){ mx=0;my=10; msg="mouse exited"; repaint(); } public void mousePressed(MouseEvent me){ mx=me.getX(); my=me.getY(); msg="Down"; repaint(); } public void mouseReleased(MouseEvent me){ mx=me.getX(); my=me.getY(); msg="Up"; repaint(); } public void mouseDragged(MouseEvent me){ mx=me.getX(); my=me.getY(); msg="*"; showStatus("moving mouse at"+me.getX()+","+me.getY()); } public void mouseMoved(MouseEvent me){ showStatus("mouse is moving"); } public void paint(Graphics g){ g.drawString(msg,mx,my); } }

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 31: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 30

OUTPUT: D:\Lab>javac MouseDemo.java D:\Lab>appletviewer MouseDemo.java

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 32: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 31

Week 9: a) Write a Java program that creates three threads. First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every hree seconds.

import java.io.*; class One extends Thread { public void run() { for(int i=0;i<100;i++) { try{ Thread.sleep(1000); } catch(InterruptedException e){ System.out.println(e); } System.out.println("Good Morning"); } } } class Two extends Thread { public void run() { for(int i=0;i<100;i++) { try{ Thread.sleep(2000); } catch(InterruptedException e) { System.out.println(e); } System.out.println("Hello "); } } } class Three implements Runnable { public void run() { for(int i=0;i<100;i++) { try{ Thread.sleep(3000); } catch(InterruptedException e){ System.out.println(e); } System.out.println("Wel come"); } } } class ThreadEx { public static void main(String[] args) { One t1=new One(); Two t2=new Two();

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 33: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 32

Three tt=new Three(); Thread t3=new Thread(tt); t1.setName("One"); t2.setName("Two"); t3.setName("Three"); System.out.println(t1); System.out.println(t2); System.out.println(t3); Thread t=Thread.currentThread(); System.out.println(t); t1.start();t2.start();t3.start(); } } OUTPUT: D:\Lab>javac ThreadEx.java D:\Lab>java ThreadEx Thread[One,5,main] Thread[Two,5,main] Thread[Three,5,main] Thread[main,5,main] Good Morning Good Morning Hello Wel come Good Morning Hello Good Morning Good Morning Hello Wel come Good Morning Good Morning Hello Good Morning

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 34: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 33

c) Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication import java.io.*; class Thread1 { int n; boolean valueset=false; synchronized int get() { if (!valueset) try { wait(); } catch (Exception e) { System.out.println("Excepton occur at : "+e); } System.out.println("get" +n); try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Excepton occur at : "+e); } valueset=false; notify(); return n; } synchronized int put(int n) { if (valueset) try { wait(); } catch (Exception e) { System.out.println("Excepton occur at : "+e); } this.n=n; valueset=true; System.out.println("put"+n); try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Excepton occur at : "+e); } notify(); return n; }

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 35: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 34

} class Producer implements Runnable { Thread1 t; Producer(Thread1 t) { this.t=t; new Thread(this,"Producer").start(); } public void run() { int i=0; while (true) { t.put(i++); } } } class Consumer implements Runnable { Thread1 t; Consumer(Thread1 t) { this.t=t; new Thread(this,"Consumer").start(); } public void run() { int i=0; while (true) { t.get(); } } } class ProducerConsumer { public static void main(String[] args) throws IOException { Thread1 t=new Thread1(); new Producer(t); new Consumer(t); System.out.println("Press Control+c to exit"); } } OUTPUT: D:\Lab>javac ProducerConsumer.java D:\Lab>java ProducerConsumer put0 Press Control+c to exit get0 put1 get1 put2 get2 put3

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 36: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 35

Week 10: Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception Display the exception in a message dialog box. import java.awt.*; import java.awt.event.*; class NumDiv extends Frame implements ActionListener { TextField num1, num2, res; Button division; String msg=" "; Label l1,l2; NumDiv() { l1=new Label("Enter First Number"); l2=new Label("Enter Second Number"); num1=new TextField(30); num2=new TextField(30); res=new TextField(100); division=new Button("Division"); setLayout(null); setForeground(Color.blue); setFont(new Font("Ariel", Font.BOLD,15)); l1.setBounds(100,100,200,30); l2.setBounds(100,150,200,30); num1.setBounds(350,100,100,30); num2.setBounds(350,150,100,30); division.setBounds(200,200,100,30); res.setBounds(100,250,300,30); add(l1); add(num1); add(l2); add(num2); add(res); add(division); setSize(600,600); setVisible(true); setTitle("DIvision"); setBackground(new Color(250,160,250)); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); division.addActionListener(this); } public void paint(Graphics g) { g.setColor(Color.black); g.setFont(new Font("Arial",Font.BOLD,30)); } public static void main(String[] args)

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 37: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 36

{ new NumDiv(); } public void actionPerformed(ActionEvent e) { msg=""; int n1=1;int n2=1;int temp=1; String s1=num1.getText(); String s2=num2.getText(); try { n1=Integer.parseInt(s1); n2=Integer.parseInt(s2); } catch(NumberFormatException ex) { MyDialog d=new MyDialog(this, "NumberFormatException Dialog",ex); } if(n2==0) { try{ temp=n1/n2; } catch(ArithmeticException e1) { MyDialog d=new MyDialog(this,"ArithmaticExceptionDialog",e1); } } else { msg+=n1/n2; } res.setText(msg); } } class MyDialog extends Dialog { MyDialog(Frame f, String s, Exception e) { super(f,s,false); setVisible(true); setSize(500,500); setForeground(Color.blue); setFont(new Font("Arial",Font.BOLD,15)); setLayout(null); Label l=new Label(e.toString()); l.setBounds(20,100,500,30); add(l); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); } }

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 38: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 37

OUTPUT: D:\Lab>javac NumDiv.java D:\Lab>java NumDiv

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 39: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 38

Week 11: a) Write a java program that simulates a traffic light. The program lets the user select one of three

lights: red,yellow or green. When a radio button is selected, the light is turned on, and only one light can be on at a time. No light is on when the program starts. import java.awt.*; import java.awt.event.*; class Traffic extends Frame implements ItemListener { String clr=""; Traffic() { Checkbox c1,c2,c3; CheckboxGroup cbg=new CheckboxGroup(); c1=new Checkbox("red",true,cbg); c2=new Checkbox("green",true,cbg); c3=new Checkbox("yellow",true,cbg); setSize(500,500); setTitle("Traffic Signal"); setVisible(true); setLayout(new FlowLayout(FlowLayout.CENTER)); add(c1); add(c2); add(c3); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new Traffic(); } public void itemStateChanged(ItemEvent e) { clr=(e.getItem()).toString(); repaint(); } public void paint(Graphics g) { g.drawString("Traffic signals",200,250); g.drawOval(200,300,50,50); g.drawOval(200,400,50,50); g.drawOval(200,500,50,50); g.drawRect(180,200,100,400); if(clr.equals("red")) { g.setColor(Color.red); g.fillOval(200,300,50,50); } if(clr.equals("green")) {

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 40: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 39

g.setColor(Color.green); g.fillOval(200,400,50,50); } if(clr.equals("yellow")) { g.setColor(Color.yellow); g.fillOval(200,500,50,50); } } }

OUTPUT: D:\Lab>javac Traffic.java D:\Lab>java Traffic

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 41: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 40

b) Write a Java program that allows the user to draw lines, rectangle and ovals. import java.awt.*; import java.awt.event.*; import java.util.*; class draw extends Frame { draw(){ setTitle("Drawing different Shapes"); setSize(500,500); setVisible(true); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } } ); } public static void main(String[] args) { new draw(); } public void paint(Graphics g) { g.setColor(Color.blue); g.drawLine(100,80,350,80); g.drawRect(140,140,50,100); g.fillRect(200,140,70,70); g.drawRoundRect(300,140,100,150,60,60); g.drawOval(140,340,100,100); g.fillOval(300,340,100,100); g.setColor(Color.magenta); g.drawArc(120,500,70,50,0,-90); g.fillArc(180,500,100,150,10,+60); g.setColor(Color.green); int x[]={300,500,380,550,670}; int y[]={550,580,600,680,490}; g.drawPolygon(x,y,5); } }

OUTPUT:

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 42: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 41

Week 12: a) Write a java program to create an abstract class named Shape that contain 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 class contains only the method numberOfSides() that shows the number of sides in the given geometrical figures. import java.awt.*; import java.awt.event.*; abstract class Shape { abstract int numberOfSides(); } class Trapezoid extends Shape { int numberOfSides() { return 4; } } class Triangle extends Shape { int numberOfSides() { return 3; } } class Hexagon extends Shape { int numberOfSides() { return 6; } } class ShapeMain extends Frame implements TextListener { TextField f; int n=0,nl=0; Shape S; ShapeMain() { setSize(500,500); setVisible(true); setTitle("Shape"); setLayout(new FlowLayout(FlowLayout.LEFT)); Label l=new Label("Enter number"); f=new TextField("0",10); add(l); add(f); f.addTextListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } } ); } public static void main(String[] args) { new ShapeMain(); } public void paint(Graphics g)

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 43: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 42

{ int x[]={100,150,175,150,100,75}; int y[]={100,100,150,200,200,150}; g.drawPolygon(x,y,n); g.drawString("Number of sides are:"+nl,300,300); } public void textValueChanged(TextEvent e) { Trapezoid t1=new Trapezoid(); Triangle t2=new Triangle(); Hexagon h=new Hexagon(); String msg=f.getText(); n=Integer.parseInt(msg); if(msg.equals("3")) { S=t2; nl=S.numberOfSides(); } if(msg.equals("4")) { S=t1; nl=S.numberOfSides(); } if(msg.equals("6")) { S=h; nl=S.numberOfSides(); } repaint(); } }

OUTPUT: D:\Lab>javac ShapeMain.java D:\Lab>java ShapeMain

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 44: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 43

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 45: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 44

b) Suppose that a table 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 separated by commas. Write a java program to display the table using JTable component. import java.io.*; import java.awt.*; import javax.swing.*; import java.util.*; class table extends JFrame { static int r=0,i=0,j=0,c=0; static Object d[][]; static Object h[]; table() { setVisible(true); setSize(500,500);

Label l=new Label("Malla Reddy Institue of Technology"); setTitle("TABLE DEMO"); setLayout(new FlowLayout(FlowLayout.CENTER)); JTable j=new JTable(d,h); JScrollPane jsp=new JScrollPane(j); add(l); add(jsp); } public static void main(String[] args) throws IOException { FileReader f=new FileReader("file.txt"); BufferedReader b=new BufferedReader(f); String s=b.readLine(); StringTokenizer g=new StringTokenizer(s,","); c=g.countTokens(); h=new Object[c]; while(g.hasMoreTokens()) { h[i]=g.nextToken(); i++; } while((s=b.readLine())!=null) r++; d=new Object[r][c]; BufferedReader br=new BufferedReader(new FileReader("file.txt")); String e=br.readLine(); for(i=0;i<r;i++) { e=br.readLine(); StringTokenizer st=new StringTokenizer(e,","); while(st.hasMoreTokens()) { d[i][j]=st.nextToken(); j++; } j=0; } new table(); } }

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net

Page 46: Object Oriented Programming Lab - Sree Vahini

Object Oriented Programming Lab

Object Oriented Programming Lab 45

OUTPUT: D:\Lab>javac table.java D:\Lab>java table

www.jntuworld.com || www.android.jntuworld.com || www.jwjobs.net || www.android.jwjobs.net

www.jntuworld.com || www.jwjobs.net