Sie sind auf Seite 1von 24

www.jntuworld.com Compiled By : Bharath Annamaneni & Hari Vardhan Yerramsetty For http://www.jntuworld.com . JN TU W OR L D www.jntuworld.com www.jntuworld.

com 1 OBJECT ORIENTED PROGRAMMING LAB Week1 : 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 discriminant b2-4ac is negative, display a message stating that there are no real solutions. import java.io.*; import java.io.*; class root { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a=Integer.parseInt(br.readLine()); int b=Integer.parseInt(br.readLine()); int c=Integer.parseInt(br.readLine()); int d=((b*b)-(4*a*c)); if(d>0) { System.out.print("roots are real and distinct"); } if(d==0) { System.out.print("roots are real"); } if(d<0) { System.out.print("there is no solution"); } } JN TU W OR L D www.jntuworld.com www.jntuworld.com 2 OBJECT ORIENTED PROGRAMMING LAB } b) 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.lang.*; class fibonacci { public static void main(String args[]) throws IOException { int a=Integer.parseInt(args[0]); int b=Integer.parseInt(args[1]); int n=Integer.parseInt(args[2]); int c=0; while(c<n) { c=a+b; System.out.print(c); a=b; b=c; } }

} Week 2 : a) Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer. JN TU W OR L D www.jntuworld.com www.jntuworld.com 3 OBJECT ORIENTED PROGRAMMING LAB import java.lang.*; import java.io.*; class prime { public static void main(String args[]) { int n=Integer.parseInt(args[0]); for(int r=0;r<n;r++) { int t=0; for(int i=1;i<r;i++) { if (r%i==0) { t++; } } if(t<2) { System.out.print(r); System.out.print(" "); } } } } b) Write a Java program to multiply two given matrices. import java.lang.*; import java.io.*; class arraymul JN TU W OR L D www.jntuworld.com www.jntuworld.com 4 OBJECT ORIENTED PROGRAMMING LAB { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("enter no of rows"); int m=Integer.parseInt(br.readLine()); System.out.print("enter no of columns"); int n=Integer.parseInt(br.readLine()); int a[][]=new int[m][n]; int i,j,k; { for( i=0;i<m;i++) { for(j=0;j<n;j++) { a[i][j]=Integer.parseInt(br.readLine()); } } System.out.print("enter no of rows"); int p=Integer.parseInt(br.readLine()); System.out.print("enter no of columns"); int q=Integer.parseInt(br.readLine());

int b[][]=new int[p][q]; { for( i=0;i<p;i++) { for( j=0;j<q;j++) { b[i][j]=Integer.parseInt(br.readLine()); } } JN TU W OR L D www.jntuworld.com www.jntuworld.com 5 OBJECT ORIENTED PROGRAMMING LAB } int c[][]=new int[m][i]; if(n==p) { 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]=c[i][j]+(a[i][k]*b[k][j]); } } } for(i=0;i<m;i++) { for(j=0;j<q;j++) { System.out.println(c[i][j]); } } } } } } . c) Write a Java Program that reads a line of integers, and then displays each in teger, and the sum of all the integers (Use StringTokenizer class of java.util) import java.io.*; class sum { public static void main(String args[])throws IOException JN TU W OR L D www.jntuworld.com www.jntuworld.com 6 OBJECT ORIENTED PROGRAMMING LAB { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,n,sum=0; System.out.print("enter the no of elements"); n=Integer.parseInt(br.readLine()); System.out.print("the elements are"); for(i=0;i<n;i++) { int ni=Integer.parseInt(br.readLine()); sum=sum+ni; } System.out.print("the sum is"+sum); } } Week 3 :

a) Write a Java program that checks whether a given string is a palindrome or no t. class Palindrome { public static void main(String args[]) { String s=args[0]; int len,i=0,n,c=0,p; len=s.length(); n=len/2; p=len-n+1; while(i<len/2) { JN TU W OR L D www.jntuworld.com www.jntuworld.com 7 OBJECT ORIENTED PROGRAMMING LAB if(s.charAt [i]==s.charAt(p)) c++; i++; p--; } if(c==len/2) { System.out.println("palindrom"); } else { System.out.println("not palindrom"); } } } b) Write a Java program for sorting a given list of names in ascending order. import java.lang.*; import java.io.*; class asc { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("enter how many strings"); int n=Integer.parseInt(br.readLine()); String x[]=new String[n]; System.out.print("enter "+n+" strings"); JN TU W OR L D www.jntuworld.com www.jntuworld.com 8 OBJECT ORIENTED PROGRAMMING LAB for(int i=0;i<n;i++) { x[i]=br.readLine(); } String s=new String(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(x[i].compareTo(x[j])<6) { s=x[i]; x[i]=x[j]; x[j]=s; } }

} System.out.print("string in alphebetical order are"); for(int i=0;i<n;i++) { System.out.println(x[i]); } } } c) Write a Java program to make frequency count of words in a given text. class Count { JN TU W OR L D www.jntuworld.com www.jntuworld.com 9 OBJECT ORIENTED PROGRAMMING LAB public static void main(String args[]) { int i,c=0; for(i=0;i<args.length;i++) { System.out.println(args[i]); c++; } System.out.println("number of words="+c); } } Week 4 : a) Write a Java program that reads a file name from the user, then displays info rmation about whether the file exists, whether the file is readable, whether the file is writable, the typ e of file and the length of the file in bytes. import java.io.*; class FileDemo { public static void main(String args[]) { File f1=new File("/java/copyright","Bharath.java"); System.out.println("file name"+f1.getName()); System.out.println("path"+f1.getPath()); System.out.println("parent"+f1.getParent()); System.out.println(f1.exists()); System.out.println(f1.canRead()); System.out.println(f1.canWrite()); System.out.println(f1.isDirectory()); JN TU W OR L D www.jntuworld.com www.jntuworld.com 10 OBJECT ORIENTED PROGRAMMING LAB System.out.println(f1.isFile()); System.out.println(f1.lastModified()); System.out.println(f1.length()); System.out.println(f1.delete()); } } b) Write a Java program that reads a file and displays the file on the screen, w ith a line number before each line. import java.io.*; class FileDemo1 { public static void main(String args[])throws Exception { int c=0; String s="i+ \n is \n java \n program \n"; char buffer[]=new char[s.length()];

s.getChars(0,s.length(),buffer,0); FileWriter f1=new FileWriter("c:/index.txt"); f1.write(buffer); f1.close(); FileReader fr=new FileReader("c:/index.txt"); BufferedReader br=new BufferedReader(fr); String t; while((t=br.readLine())!=null) { c++; JN TU W OR L D www.jntuworld.com www.jntuworld.com 11 OBJECT ORIENTED PROGRAMMING LAB System.out.println(c+t); } fr.close(); } } c) Write a Java program that displays the number of characters, lines and words in a text file. import javax.swing.*; import java.io.*; import java.util.*; public class Count { public static void main(String args[]) { try { String s=JOptionPane.showInputDialog("Enter the file name : "); FileInputStream f=new FileInputStream(s); DataInputStream d=new DataInputStream(f); String data; StringTokenizer st; int words=0,chars=0,i=0; while((data=d.readLine())!=null) { i++; st=new StringTokenizer(data); words+=st.countTokens(); chars+=data.length(); } System.out.println("total words \n" +words); JN TU W OR L D www.jntuworld.com www.jntuworld.com 12 OBJECT ORIENTED PROGRAMMING LAB System.out.println("total chras \n" +chars); System.out.println("total lines \n" +i ); f.close(); } catch(Exception) System.out.println("err"+e); } } } Week 5 : Write a Java program that: i) Implements stack ADT. import java.io.*; class stack { int stack[]=new int[10];

int tos; stack() { tos=-1; } void push(int item) { if(tos==9) System.out.println("stack is full"); else stack[++tos]=item; } JN TU W OR L D www.jntuworld.com www.jntuworld.com 13 OBJECT ORIENTED PROGRAMMING LAB int pop() { if(tos<0) { System.out.println("stack underflow"); return 0; } else return stack[tos--]; } } class teststack { public static void main(String args[]) { stack mystack1=new stack(); stack mystack2=new stack(); for(int i=0;i<10;i++) mystack1.push(i); for(int i=10;i<20;i++) mystack2.push(i); System.out.println("stack in my stack1:"); for(int i=0;i<10;i++) System.out.println(mystack1.pop()); System.out.println("stack in my stack2:"); for(int i=0;i<10;i++) System.out.println(mystack2.pop()); } } JN TU W OR L D www.jntuworld.com www.jntuworld.com 14 OBJECT ORIENTED PROGRAMMING LAB ii) Converts infix expression into Postfix form . import java.io.*; class stack { char stack1[]=new char[20]; int top; void push(char ch) { top++; stack1[top]=ch; } char pop() { char ch; ch=stack1[top];

top--; return ch; } int pre(char ch) { switch(ch) { case '-':return 1; case '+':return 1; case '*':return 2; case '/':return 2; } return 0; } boolean operator(char ch) { JN TU W OR L D www.jntuworld.com www.jntuworld.com 15 OBJECT ORIENTED PROGRAMMING LAB if(ch=='/'||ch=='*'||ch=='+'||ch=='-') return true; else return false; } boolean isAlpha(char ch) { if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9') return true; else return false; } void postfix(String str) { char output[]=new char[str.length()]; char ch; int p=0,i; for(i=0;i<str.length();i++) { ch=str.charAt(i); if(ch=='(') { push(ch); } else if(isAlpha(ch)) { output[p++]=ch; } else if(operator(ch)) { if(stack1[top]==0||(pre(ch)>pre JN TU W OR L D www.jntuworld.com www.jntuworld.com 16 OBJECT ORIENTED PROGRAMMING LAB (stack1[top]))||stack1[top]=='(') { push(ch); } } else if(pre(ch)<=pre(stack1[top])) { output[p++]=pop(); push(ch);

} else if(ch=='(') { while((ch=pop())!='(') { output[p++]=ch; } } } while(top!=0) { output[p++]=pop(); } for(int j=0;j<str.length();j++) { System.out.print(output[j]); } } } class InToPost { public static void main(String[] args)throws Exception JN TU W OR L D www.jntuworld.com www.jntuworld.com 17 OBJECT ORIENTED PROGRAMMING LAB { String s; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); stack b=new stack(); System.out.println("Enter input string"); s=br.readLine(); System.out.println("Input String:"+s); System.out.println("Output String:"); b.postfix(s); } } iii) Evaluates the postfix expression. import java.io.*; import java.util.*; class StackDemo { static int index,pos; int T; float stk[]; StackDemo() { stk=new float[10]; T=-1; index=0; pos=0; } void push(float s) { JN TU W OR L D www.jntuworld.com www.jntuworld.com 18 OBJECT ORIENTED PROGRAMMING LAB if(T>=19) { System.out.println("Stack overflow"); System.exit(0); }else{

T=T+1; stk[T]=s; } } float pop() { float num; if(T==-1) { System.out.println("Stack is empty"); return(0); } else { num=stk[T]; T--; } return(num); } float ExpEval(char sfix[],float data[]) { int j=0; float op1,op2,fs; char ch; while(sfix[j]!='\0') { JN TU W OR L D www.jntuworld.com www.jntuworld.com 19 OBJECT ORIENTED PROGRAMMING LAB ch=sfix[j]; if(sfix[j]>='a'||sfix[j]>= 'A'&&sfix[j]<='z'||sfix[j]<='Z') { push(data[j]); } else { op2=pop(); op1=pop(); switch(ch) { case '+':push(op1+op2); break; case '-':push(op1-op2); break; case '*':push(op1*op2); break; case '/':push(op1/op2); break; case '%':push(op1%op2); break; } } j++; } fs=pop(); return(fs); } } class EvalPostFix JN TU W OR L D www.jntuworld.com www.jntuworld.com

20 OBJECT ORIENTED PROGRAMMING LAB { public static void main(String args[]) { String str; char postfix[]=new char[25]; float number[]=new float[25]; int j=0; try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a postfix expression:"); str=br.readLine(); str.getChars(0,str.length(),postfix,0); while(postfix[j]!='\0') { if(postfix[j]>='a'||postfix[j] >='A'&&postfix[j]<='z'||postfix[j]<='Z') { System.out.println("enter a number for%c:"+postfix[j]); number[j]=Integer.parseInt(br.readLine()); } j++; } } catch(Exception e) { System.out.println("Exception \n Read:"+e); } StackDemo s1=new StackDemo(); System.out.println("The result is "+s1.ExpEval(postfix,number)); JN TU W OR L D www.jntuworld.com www.jntuworld.com 21 OBJECT ORIENTED PROGRAMMING LAB } } Week 6 : a) Develop an applet that displays a simple message. //<applet code="AppletDemo.class" height="300" width="300" > </applet> import java.applet.*; import java.awt.*; public class AppletDemo extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.drawString("BANDARI SRINIVAS INSTITUTE OF TECHNOLOGY ",70,70); } } b) Develop an applet that receives an integer in one text field, and computes it s factorial Value and returns it in another text field, when the button named Compute is clicked. //<applet code="FactorialApplet.class" width="300" height="500" > </applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; public class FactorialApplet extends JApplet implements ActionListener { JPanel p1,p2; JLabel label1,label2;

JTextField input,result; JButton compute; public void init() { JN TU W OR L D www.jntuworld.com www.jntuworld.com 22 OBJECT ORIENTED PROGRAMMING LAB Container con=getContentPane(); con.setLayout(new BorderLayout()); label1=new JLabel("Enter the number : "); label2=new JLabel("Factorial is : "); input= new JTextField(5); result= new JTextField(5); compute =new JButton("Compute"); compute.addActionListener(this); p1=new JPanel(); p2=new JPanel(); p1.setBackground(Color.pink); p2.setBackground(Color.green); p1.add(label1); p1.add(input); p1.add(label2); p1.add(result); p2.add(compute); con.add(p1,BorderLayout.NORTH); con.add(p2,BorderLayout.CENTER); } public void actionPerformed(ActionEvent ae) { int fact=1; int number=Integer.parseInt(input.getText()); if (ae.getSource()==compute) { for (int i=1;i<=number;i++) { fact=fact*i; } result.setText(""+fact); JN TU W OR L D www.jntuworld.com www.jntuworld.com 23 OBJECT ORIENTED PROGRAMMING LAB } } } Week 7 : Write a Java program that works as a simple calculator. Use a grid layout to arr ange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result. //<applet code="Calculator.class" height="150" width="700"> </applet> import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Calculator extends Applet implements ActionListener { JTextField t1,t2,t3; JLabel l1,l2,l3; JButton b1,b2,b3,b4; JPanel p1,p2; public void init() { p1=new JPanel();

p2=new JPanel(); p1.setBackground(Color.gray); p2.setBackground(Color.gray); setBackground(Color.lightGray); l1=new JLabel("Enter the First number :"); p1.add(l1); t1=new JTextField(10); p1.add(t1); l2=new JLabel("Enter the Second number :"); JN TU W OR L D www.jntuworld.com www.jntuworld.com 24 OBJECT ORIENTED PROGRAMMING LAB p1.add(l2); t2=new JTextField(10); p1.add(t2); l3=new JLabel("Result"); p1.add(l3); t3=new JTextField(10); p1.add(t3); b1=new JButton("ADD"); p2.add(b1); b1.addActionListener(this); b2=new JButton("SUB"); p2.add(b2); b2.addActionListener(this); b3=new JButton("MUL"); p2.add(b3); b3.addActionListener(this); b4=new JButton("DIVISION"); p2.add(b4); b4.addActionListener(this); add(p1,BorderLayout.NORTH); add(p2,BorderLayout.CENTER); t1.setBackground(Color.yellow); t2.setBackground(Color.yellow); t3.setBackground(Color.yellow); } public void actionPerformed(ActionEvent ae) { try { if (ae.getSource()==b1) { JN TU W OR L D www.jntuworld.com www.jntuworld.com 25 OBJECT ORIENTED PROGRAMMING LAB int x=Integer.parseInt(t1.getText()); int y=Integer.parseInt(t2.getText()); int sum=x+y; t3.setText(" "+sum); } if (ae.getSource()==b2) { int x=Integer.parseInt(t1.getText()); int y=Integer.parseInt(t2.getText()); int sub=x-y; t3.setText(" "+sub); } if (ae.getSource()==b3) { int x=Integer.parseInt(t1.getText()); int y=Integer.parseInt(t2.getText());

int mul=x*y; t3.setText(" "+mul); } if (ae.getSource()==b4) { int x=Integer.parseInt(t1.getText()); int y=Integer.parseInt(t2.getText()); int div=x/y; t3.setText(" "+div); } } catch (Exception e) { JOptionPane.showMessageDialog(null,e); } JN TU W OR L D www.jntuworld.com www.jntuworld.com 26 OBJECT ORIENTED PROGRAMMING LAB } } Week 8 : a) Write a Java program for handling mouse events. import java.awt.*; import java.applet.Applet; import java.awt.event.*; /*<applet code="Mouseevents"width=200 height=100> </applet>*/ public class Mouseevents extends Applet implements MouseListener,MouseMotionList ener { String msg=""; int x=0,y=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { x=10; y=20; msg="mouse clicked"; repaint(); } public void mouseEntered(MouseEvent me) { x=10; y=20; JN TU W OR L D www.jntuworld.com www.jntuworld.com 27 OBJECT ORIENTED PROGRAMMING LAB msg="mouse entered"; repaint(); } public void mouseExited(MouseEvent me) { x=10; y=20; msg="mouse exited"; repaint(); } public void mousePressed(MouseEvent me)

{ x=me.getX(); y=me.getY(); msg="down"; repaint(); } public void mouseReleased(MouseEvent me) { x=me.getX(); y=me.getY(); msg="up"; repaint(); } public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY(); msg="*"; showStatus("dragging mouse at"+x+","+y); repaint(); JN TU W OR L D www.jntuworld.com www.jntuworld.com 28 OBJECT ORIENTED PROGRAMMING LAB } public void mouseMoved(MouseEvent me) { showStatus("moving mouse at"+me.getX()+","+me.getY()); } public void paint(Graphics g) { g.drawString(msg,x,y); } } Week 9 : a) Write a Java program that creates three threads. First thread displays Good Mo rning every one second, the second thread displays Hello every two seconds and the third thread displays lcome every three seconds. class A extends Thread { synchronized public void run() { try { while(true) { sleep(10); System.out.println("good morning"); } } catch(Exception e) { } JN TU W OR L D www.jntuworld.com www.jntuworld.com 29 OBJECT ORIENTED PROGRAMMING LAB } } class B extends Thread { synchronized public void run() {

We

try { while(true) { sleep(20); System.out.println("hello"); } } catch(Exception e) { } } } class C extends Thread { synchronized public void run() { try { while(true) { sleep(30); JN TU W OR L D www.jntuworld.com www.jntuworld.com 30 OBJECT ORIENTED PROGRAMMING LAB System.out.println("welcome"); } } catch(Exception e) { } } } class ThreadDemo { public static void main(String args[]) { A t1=new A(); B t2=new B(); C t3=new C(); t1.start(); t2.start(); t3.start(); } } b) Write a Java program that correctly implements producer consumer problem usin g the concept of inter thread communication. class Q { boolean valueSet=false; JN TU W OR L D www.jntuworld.com www.jntuworld.com 31 OBJECT ORIENTED PROGRAMMING LAB int n; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) {

System.out.println("Exception is:"+e); } System.out.println("got:"+n); notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println JN TU W OR L D www.jntuworld.com www.jntuworld.com 32 OBJECT ORIENTED PROGRAMMING LAB ("\n Exception in put:"+e); } this.n=n; valueSet=true; System.out.println("\nput:"+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) JN TU W OR L D www.jntuworld.com www.jntuworld.com 33 OBJECT ORIENTED PROGRAMMING LAB { this.q=q; new Thread(this,"Consumer").start(); } public void run() { while(true) q.get(); } } class ProdConsDemo { public static void main(String args[])

{ Q q=new Q(); new Producer(q); new Consumer(q); System.out.println("\n press ctrl+c to stop"); } } Week 10 : Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the textfields, 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 a NumberFormatException. If Num2 were Zero, the program would throw an ArithmeticE xception Display the exception in a message dialog box. import java.awt.*; JN TU W OR L D www.jntuworld.com www.jntuworld.com 34 OBJECT ORIENTED PROGRAMMING LAB import java.awt.event.*; import java.applet.*; /*<applet code="Div"width=230 height=250> </applet>*/ public class Div extends Applet implements ActionListener { String msg; TextField num1,num2,res;Label l1,l2,l3; Button div; public void init() { l1=new Label("Number 1"); l2=new Label("Number 2"); l3=new Label("result"); num1=new TextField(10); num2=new TextField(10); res=new TextField(10); div=new Button("DIV"); div.addActionListener(this); add(l1); add(num1); add(l2); add(num2); add(l3); add(res); add(div); } JN TU W OR L D www.jntuworld.com www.jntuworld.com 35 OBJECT ORIENTED PROGRAMMING LAB public void actionPerformed(ActionEvent ae) { String arg=ae.getActionCommand(); if(arg.equals("DIV")) { String s1=num1.getText(); String s2=num2.getText(); int num1=Integer.parseInt(s1); int num2=Integer.parseInt(s2); if(num2==0) {

try { System.out.println(" "); } catch(Exception e) { System.out.println("ArithematicException"+e); } msg="Arithemetic"; repaint(); } else if((num1<0)||(num2<0)) { try { System.out.println(""); JN TU W OR L D www.jntuworld.com www.jntuworld.com 36 OBJECT ORIENTED PROGRAMMING LAB } catch(Exception e) { System.out.println("NumberFormat"+e); } msg="NumberFormat"; repaint(); } else { int num3=num1/num2; res.setText(String.valueOf(num3)); } } } public void paint(Graphics g) { g.drawString(msg,30,70); } } Week 11 : Write a Java program that implements a simple client/server application. The cli ent sends data to a server. The server receives the data, uses it to produce a result, and then sends the re sult back to the client. The client displays the result on the console. For ex: The data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle. (Use java.net). server.java import java.net.*; JN TU W OR L D www.jntuworld.com www.jntuworld.com 37 OBJECT ORIENTED PROGRAMMING LAB import java.io.*; public class server { public static void main(String args[]) throws Exception { ServerSocket ss=new ServerSocket(2000); Socket s=ss.accept(); BufferedReader br=new BufferedReader (new InputStreamReader(s.getInputStream())); double rad,area;

String result; rad=Double.parseDouble(br.readLine()); System.out.println("From Client : "+rad); area=Math.PI*rad*rad; result="Area is "+area; PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(result); br.close(); ps.close(); s.close(); ss.close(); } } Client.java import java.net.*; import java.io.*; public class client JN TU W OR L D www.jntuworld.com www.jntuworld.com 38 OBJECT ORIENTED PROGRAMMING LAB { public static void main(String args[]) throws Exception { Socket s=new Socket("localhost",2000); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String rad; System.out.println("Enter radius of the circle "); rad=br.readLine(); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(rad); BufferedReader fs=new BufferedReader(new InputStreamReader (s.getInputStream())); String result=fs.readLine(); System.out.println("From Server : "+result); br.close(); fs.close(); ps.close(); s.close(); } } Week 12 : a) Write a java program that simulates a traffic light. The program lets the use r select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and o nly one light can be on at a time No light is on when the program starts. import java.awt.*; JN TU W OR L D www.jntuworld.com www.jntuworld.com 39 OBJECT ORIENTED PROGRAMMING LAB import java.awt.event.*; import javax.swing.*; class TrafficLight extends JFrame implements ActionListener { String msg=" " ; private JLabel label; private JTextField display; private JRadioButton r1,r2,r3; private ButtonGroup bg; private Container c;

public TrafficLight() { setLayout(new FlowLayout()); c=getContentPane(); label=new JLabel(" Traffic Light"); display =new JTextField(10); r1=new JRadioButton("RED"); r2=new JRadioButton("GREEN"); r3=new JRadioButton("YELLOW"); bg=new ButtonGroup(); c.add(label); c.add(r1); c.add(r2); c.add(r3); c.add(display); bg.add(r1); bg.add(r2); bg.add(r3); r1.addActionListener(this); r2.addActionListener(this); r3.addActionListener(this); JN TU W OR L D www.jntuworld.com www.jntuworld.com 40 OBJECT ORIENTED PROGRAMMING LAB setSize(400,400); setVisible(true); c.setBackground(Color.pink); } public void actionPerformed(ActionEvent ie) { msg=ie.getActionCommand(); if (msg.equals("RED")) { c.setBackground(Color.RED); display.setText(msg+ " :TURN ON"); } else if (msg.equals("GREEN")) { c.setBackground(Color.GREEN); display.setText(msg+ " :TURN ON"); } else if (msg.equals("YELLOW")) { c.setBackground(Color.YELLOW); display.setText(msg+ " :TURN ON"); } } public static void main(String args[]) { TrafficLight light=new TrafficLight(); light.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } b) Write a Java program that allows the user to draw lines, rectangles and ovals . JN TU W OR L D www.jntuworld.com www.jntuworld.com 41 OBJECT ORIENTED PROGRAMMING LAB //<applet code="LinesRectsOvals.class" height="250" width="400"> </applet> import java.applet.*; import java.awt.*; import javax.swing.*;

public class LinesRectsOvals extends JApplet { public void paint(Graphics g) { super.paint(g); g.setColor(Color.red); g.drawLine(5,30,350,30); g.setColor(Color.blue); g.drawRect(5,40,90,55); g.fillRect(100,40,90,55); g.setColor(Color.cyan); g.fillRoundRect(195,40,90,55,50,50); g.drawRoundRect(290,40,90,55,20,20); g.setColor(Color.yellow); g.draw3DRect(5,100,90,55,true); g.fill3DRect(100,100,90,55,false); g.setColor(Color.magenta); g.drawOval(195,100,90,55); g.fillOval(290,100,90,55); } } Week 13 : 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 su ch that each one of the JN TU W OR L D www.jntuworld.com www.jntuworld.com 42 OBJECT ORIENTED PROGRAMMING LAB classes extends the class Shape. Each one of the classes contains only the metho d 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 " ); }

JN TU W OR L D www.jntuworld.com www.jntuworld.com 43 OBJECT ORIENTED PROGRAMMING LAB } class ShapeDemo { public static void main(String[] args) { JOptionPane.showMessageDialog(null,"Some of the Geometrical figures are as follo ws " ); 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]; JN TU W OR L D www.jntuworld.com www.jntuworld.com 44 OBJECT ORIENTED PROGRAMMING LAB 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) JN TU W OR L D www.jntuworld.com www.jntuworld.com 45 OBJECT ORIENTED PROGRAMMING LAB { 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); } }

Das könnte Ihnen auch gefallen