Vous êtes sur la page 1sur 18

1.) Write a Java program that prints all real solutions to the quadratic equatio n ax2 + bx + c = 0.

Read in a, b, c and use the quadratic formula. If the discri minant b2 -4ac is negative, display a message stating that there are no real sol utions. public class Quadratic { public static void main(String args[]) { double a,b,c,root1,root2; a=3.0; b=4.0; c=2.0; if((b*b-4*a*c)==0) { System.out.println("\n ROOTS ARE EQUAL"); root1=-b/(2*a); System.out.println("\n root "+root1); } //(www.suhritsolutions.com) if((b*b-4*a*c) > 0) { root1=-b+Math.sqrt(b*b-4*a*c)/(2*a); root2=-b-Math.sqrt(b*b-4*a*c)/(2*a); System.out.println("\nROOTS ARE REAL:\n"); System.out.println("\n root1 "+root1+"\n root2 "+root2); } //(www.suhritsolutions.com) else System.out.println("\n Imaginary Roots."); } //(www.suhritsolutions.com) } // End of Class Output ROOTS ARE REAL: root1 -5.422649730810374 root2 -6.577350269189626 2.) The Fibonacci sequence is defined by the following rule: The fist two values in the sequence are 1 and 1. Every subsequent value is the sum of the two value s preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. import javax.swing.*; public class LabPro2 { public static void main(String args[]) { String n1; int f1=1,f2=1,n,i,f3; n1=JOptionPane.showInputDialog("enter n value"); n=Integer.parseInt(n1); JOptionPane.showMessageDialog(null,"series"+f1+f2); for(i=1;i<=n;i++) { f3=f1+f2; JOptionPane.showMessageDialog(null,f3); f1=f2; f2=f3; }

} } 3.) Write a Java program that prompts the user for an integer and then prints ou t all prime numbers up to that integer. import javax.swing.*; public class LabPro3 { public static void main(String args[]) { String n1; int n,c=0,i,j; n1=JOptionPane.showInputDialog("enter n value"); n=Integer.parseInt(n1); outer: for(i=2;i<=n;i++) { for(j=2;j<=(i/2);j++) { if(i%j==0) continue outer; } JOptionPane.showMessageDialog(null,i+" "); } } } 4.) Write a Java program to multiply two given matrices. import javax.swing.*; public class BTechJavaLab6 { public static void main(String args[]) { String n,l,m=" "; int i,j,k; int a[][]=new int[3][3]; int b[][]=new int[3][3]; int c[][]=new int[3][3]; for(i=0;i<3;i++) { for(j=0;j<3;j++) { n=JOptionPane.showInputDialog(null,"enter elements of 1st matrix"); a[i][j]= Integer.parseInt(n); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { l=JOptionPane.showInputDialog(null,"enter elements of 2nd matrix"); b[i][j]= Integer.parseInt(l); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { c[i][j]=0; for(k=0;k<3;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { m=m+c[i][j]; } m=m+"\n"; JOptionPane.showMessageDialog(null,"resultant matrix is"+m); } } } 5.) Write a Java Program that reads a line of integers, and then displays each i nteger, and the sum of all the integers (Use StringTokenizer class of java.util) import javax.swing.*; import java.util.*; import java.io.*; public class LabPro7 { public static void main(String args[])throws IOException { int sum=0; String line=JOptionPane.showInputDialog("enter the line"); String k=JOptionPane.showInputDialog("enter the delemeter"); StringTokenizer wd=new StringTokenizer(line,k); while(wd.hasMoreTokens()) sum=sum+Integer.parseInt(wd.nextToken()); JOptionPane.showMessageDialog(null,"sum is"+sum); } } 6.) Write a Java program that checks whether a given string is a palindrome or n ot. Ex: MADAM is a palindrome. import java.util.*; public class LabPro4 { public static void main(String args[]) { StringBuffer sb=new StringBuffer(args[0]); String t=sb.reverse().toString(); System.out.println("reverse "+t); System.out.println("boolean results"); System.out.println("check with == "+(t==args[0])); System.out.println("check with equals "+(t.equals(args[0]))); System.out.println("given string "+args[0]); if(t.equals(args[0])) System.out.println("is a pallindrome"); else System.out.println("is not a pallindrome"); } } 7.) Write a Java program for sorting a given list of names in ascending order.

import javax.swing.*; public class LabPro5 { static String arr[]={"arun","kumar","abc"}; public static void main(String args[]) { String t=null; int size=arr.length; for(int i=0;i<size;i++) { for(int j=i+1;j<size;j++) { if(arr[j].compareTo(arr[i])<0) { t=arr[i]; arr[i]=arr[j]; arr[j]=t; } } } for(int i=0;i<size;i++) System.out.println(arr[i]); } } 8.) Write a Java program that reads a file name from the user, then displays inf ormation about whether the file exists, whether the file is readable, whether th e file is writable, the type of file and the length of the file in bytes. import java.io.*; import java.util.*; public class LabPro8 { public static void main(String args[]) { File f=new File(args[0]); System.out.println("Filename " +f.getName()); System.out.println("Filepath " +f.getPath()); System.out.println("Parent " +f.getName()); System.out.println("File size " +f.length()+" bytes"); System.out.println("is readable " +f.canRead()); System.out.println("is Writable " +f.canWrite()); System.out.println("is directory " +f.isDirectory()); System.out.println("is file " +f.isFile()); } } 9.) Write a Java program that reads a file and displays the file on the screen, with a line number before each line. */ import import public { public { try { java.io.*; java.util.*; class LabPro9 static void main(String args[])

FileInputStream f=new FileInputStream("run"); LineNumberReader lr=new LineNumberReader(new InputStreamReader(f)); String data; while((data=lr.readLine())!=null)

{ System.out.println(lr.getLineNumber()+":"+data); } System.out.println("total lines"+lr.getLineNumber()); f.close(); } catch(Exception e) {System.out.println("err"+e);} } }

10.) Write a Java program that displays the number of characters, lines and word s in a text file. import java.io.*; import java.util.*; public class LabPro10 { public static void main(String args[]) { try { FileInputStream f=new FileInputStream("run"); LineNumberReader lr=new LineNumberReader(new InputStreamReader(f)); String data; StringTokenizer st; int words=0,chars=0; while((data=lr.readLine())!=null) { st=new StringTokenizer(data); words+=st.countTokens(); chars+=data.length(); } System.out.println("total words"+words); System.out.println("total chras"+chars); System.out.println("total lines"+lr.getLineNumber()); f.close(); } catch(Exception e) {System.out.println("err"+e);} } } Week 5 : a) Write a Java program that: i) Implements stack ADT. */ import javax.swing.*; class stack { int stck[]=new int[10]; int top; String res; stack() { top=-1; } void push(int item) { if(top==9)

System.out.println("stack is full"); else stck[++top]=item; } int pop() { if(top<0) { System.out.println("stack is underflow"); return 0; } else return stck[top--]; } void display(int n) { res=" "; for(int i=0;i<n;i++) { res=res+" "+stck[i]; } JOptionPane.showMessageDialog(null,"stack output "+res); } } public class LabPro11A { public static void main(String args[]) { int ch,n=0; String r,it; stack s1=new stack(); JOptionPane.showMessageDialog(null,"welcome to 1.push(),2.pop(), 3.display()"); do { r=JOptionPane.showInputDialog("enter the choice"); ch=Integer.parseInt(r); switch(ch) { case 1:it=JOptionPane.showInputDialog("enter the data"); int p=Integer.parseInt(it); s1.push(p); n++; break; case 2:s1.pop(); n--; break; case 3:s1.display(n); break; } }while(ch<4); } }

11.) ii) Converts infix expression into Postfix form iii) Evaluates the postfix expression

import javax.swing.*; class LabPro11B { int top; char s[]=new char[100]; infix() { top=-1; } public void push(char x) { top++; if(top>100) { System.out.println("over flow"); } else { s[top]=x; } } public char pop() { top--; return s[top+1]; } } public class inf { public static void main(String args[]) { String post=" "; String in; in=JOptionPane.showInputDialog("enter info "); char ch; infix ki=new infix(); for(int i=0;i<in.length();i++) { ch=in.charAt(i); if(ch=='(') { ki.push(ch); } else if(ch=='+'||ch=='-'||ch=='*'||ch=='/') { switch(ch) { case '+':ki.push(ch);break; case '-':ki.push(ch);break; case '*':ki.push(ch);break; case '/':ki.push(ch);break; } } else if(ch==')') { char ins=ki.pop(); if(ins=='(') ins=ki.pop(); post+=ins; }

else post+=ch; } JOptionPane.showMessageDialog(null,post); } } 12.) DISPLAY A SIMPLE APPLET PROGRAM import java.awt.*; import java.applet.Applet; /*< Applet code=LabPro12 width=300 height=300> < /Applet> */ public class LabPro12 extends Applet { public void paint(Graphics g) { g.drawString ("Hello Worlds",100,100); } } 13.) Develop an applet that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named ompute is clicked. import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code=SuhritCompute width=300 height=300> </applet> */ public class SuhritCompute extends Applet implements ActionListener { Button btn,clearbtn; Label lbl1,lbl2; TextField tf1,tf2; public void init() { btn=new Button("COMPUTE"); btn.addActionListener(this); clearbtn=new Button("CLEAR"); clearbtn.addActionListener(this); tf1=new TextField(30); tf2=new TextField(30); lbl1=new Label("NUMBER"); lbl2=new Label("RESULT"); setLayout(new GridLayout(3,2)); C

add(lbl1); add(tf1); add(lbl2); add(tf2); add(btn); add(clearbtn); } public void actionPerformed(ActionEvent e) { if(e.getSource()==btn) { int a=Integer.parseInt(tf1.getText()); int fact=1; for(int i=1;i<=a;i++) fact*=i; tf2.setText(""+fact); } else { tf1.setText(""); tf2.setText(""); } } } 14. 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 fie ld to display the result. import java.awt.event.*; import java.applet.Applet; import java.awt.*; /* < applet code= LabPro14 Width=300 Height=300 > < /applet > */ public class LabPro14 extends Applet implements ActionListener { TextField t;String a;int p=0,tmp=0; Button bo,b1,b2,b3,b4,b5,b6,b7,b8,b9; Button badd,bsub,bmul,bdiv,bper,beql,bc; public void init() { t = new TextField(50); bo = new Button("0"); b1 = new Button("1"); b2 = new Button("2"); b3 = new Button("3"); b4 = new Button("4"); b5 = new Button("5"); b6 = new Button("6"); b7 = new Button("7"); b8 = new Button("8"); b9 = new Button("9"); badd = new Button("+"); bsub = new Button("-"); bmul = new Button("*"); bdiv = new Button("/"); bper = new Button("%"); bc = new Button("c");

beql = new Button("="); add(t);add(bo);add(b1); add(b2);add(b3);add(b4); add(b5);add(b6);add(b7); add(b8);add(b9);add(badd); add(bsub);add(bmul);add(bdiv); add(bper);add(bc);add(beql); bo.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); badd.addActionListener(this); bsub.addActionListener(this); bmul.addActionListener(this); bdiv.addActionListener(this); bper.addActionListener(this); bc.addActionListener(this); beql.addActionListener(this); //setLayout(new GridLayout(4,4)); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==bc) { t.setText("0"); } if(ae.getSource()==bo) { int k=Integer.parseInt(t.getText()); k=k*10+0; t.setText(String.valueOf(k)); } if(ae.getSource()==b1) { int k=Integer.parseInt(t.getText()); k=k*10+1; t.setText(String.valueOf(k)); } if(ae.getSource()==b2) { int k=Integer.parseInt(t.getText()); k=k*10+2; t.setText(String.valueOf(k)); } if(ae.getSource()==b3) { int k=Integer.parseInt(t.getText()); k=k*10+3; t.setText(String.valueOf(k)); } if(ae.getSource()==b4) { int k=Integer.parseInt(t.getText()); k=k*10+4;

t.setText(String.valueOf(k)); } if(ae.getSource()==b5) { int k=Integer.parseInt(t.getText()); k=k*10+5; t.setText(String.valueOf(k)); } if(ae.getSource()==b6) { int k=Integer.parseInt(t.getText()); k=k*10+6; t.setText(String.valueOf(k)); } if(ae.getSource()==b7) { int k=Integer.parseInt(t.getText()); k=k*10+7; t.setText(String.valueOf(k)); } if(ae.getSource()==b8) { int k=Integer.parseInt(t.getText()); k=k*10+8; t.setText(String.valueOf(k)); } if(ae.getSource()==b9) { int k=Integer.parseInt(t.getText()); k=k*10+9; t.setText(String.valueOf(k)); } if(ae.getSource()==badd) { tmp=Integer.parseInt(t.getText()); p=1; t.setText("0"); } if(ae.getSource()==bsub) { tmp=Integer.parseInt(t.getText()); p=2; t.setText("0"); } if(ae.getSource()==bmul) { tmp=Integer.parseInt(t.getText()); p=3; t.setText("0"); } if(ae.getSource()==bdiv) { tmp=Integer.parseInt(t.getText()); p=4; t.setText("0"); } if(ae.getSource()==bper) { tmp=Integer.parseInt(t.getText()); p=5;

t.setText("0"); } if(ae.getSource()==beql) { float newval=Integer.parseInt(t.getText()); float res=0; switch(p) { case 1: res=tmp+newval; break; case 2: res=tmp-newval; break; case 3: res=tmp*newval; break; case 4: res=tmp/newval; break; case 5: res=tmp%newval; break; } t.setText(String.valueOf(res)); } } } 15.) Write a Java program for handling mouse events. import java.awt.*; import java.awt.event.*; import java.applet.Applet; /* < applet code="LabPro15" width=300 height=100> < /applet> */ public class LabPro15 extends Applet implements MouseListener { String msg="welcome";int x=100,y=100; public void init() { addMouseListener(this); } public void paint(Graphics g) { g.drawString(msg,x,y); } public void update(Graphics g) { paint(g); } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { msg="to";x=150;y=150; repaint();

} public void mouseReleased(MouseEvent e) { msg="gmrit";x=200;y=200; repaint(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } 15.) 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 th e third thread displays Welcome every three seconds. class tst implements Runnable { String name; Thread t; Arun(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("newThread : " +t); t.start(); } public void run() { try { for(int i=5;i > 0;i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + "exiting"); } } class LabPro16 { public static void main(String args[]) { new tst("Good Morning"); new tst("Hello"); new tst("Welcome"); try { Thread.sleep(10000); } catch(InterruptedException e) { System.out.println("Main thread Interrupted");

} System.out.println("Main thread exiting"); } } class LabPro17 { int n; boolean vs = false; synchronized int get() { if(!vs) try{wait();} catch(InterruptedException e) { System.out.println("InterruptedException caught");} System.out.println("got:" + n); vs = false; notify(); return n; } synchronized int put(int n) { if(vs) try{wait();} catch(InterruptedException e) { System.out.println("InterruptedException caught");} this.n = n; vs = true; System.out.println("put:" + n); notify(); return n; } } class Producer implements Runnable { LabPro17 k; Producer(LabPro17 k) { this.k = k; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) {k.put(i++);} } } class Consumer implements Runnable { LabPro17 k; Consumer(LabPro17 k) { this.k = k; new Thread(this, "Consumer").start(); } public void run() { while(true) {k.get();} }

} class PCFixed { public static void main(String args[]) { LabPro17 k = new LabPro17(); new Producer(k); new Consumer(k); System.out.println("press control - c to stop. "); } } 16.) 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 N um1 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 NumberFormatExce ption. If Num2 were Zero, the program would throw an ArithmeticException Display the exception in a message dialog box. import import import public { Container c; JButton btn; JLabel lbl1,lbl2,lbl3; JTextField tf1,tf2,tf3; JPanel p; SuhritDivision() { super("Exception Handler"); c=getContentPane(); c.setBackground(Color.red); btn=new JButton("DIVIDE"); btn.addActionListener(this); tf1=new JTextField(30); tf2=new JTextField(30); tf3=new JTextField(30); lbl1=new JLabel("NUM 1"); lbl2=new JLabel("NUM 2"); lbl3=new JLabel("RESULT"); p=new JPanel(); p.setLayout(new GridLayout(3,2)); p.add(lbl1); p.add(tf1); p.add(lbl2); p.add(tf2); p.add(lbl3); p.add(tf3); c.add(new JLabel("Division"),"North"); c.add(p,"Center"); c.add(btn,"South"); } public void actionPerformed(ActionEvent e) { javax.swing.*; java.awt.*; java.awt.event.*; class SuhritDivision extends JFrame implements ActionListener

if(e.getSource()==btn) { try { int a=Integer.parseInt(tf1.getText()); int b=Integer.parseInt(tf2.getText()); int c=a/b; tf3.setText(""+c); } catch(NumberFormatException ex) { tf3.setText("--"); JOptionPane.showMessageDialog(this,"Only Integer Division"); } catch(ArithmeticException ex) { tf3.setText("--"); JOptionPane.showMessageDialog(this,"Division by zero"); } catch(Exception ex) { tf3.setText("--"); JOptionPane.showMessageDialog(this,"Other Err "+ex.getMessage()); } } } public static void main(String args[]) { SuhritDivision b=new SuhritDivision(); b.setSize(300,300); b.setVisible(true); } } 17.) Write a Java program that allows the user to draw lines, rectangles and ova ls. import java.awt.*; import java.awt.event.*; import java.applet.*; /* < applet code=shape width=300 height=300> < /applet> */ public class LabPro19 extends Applet implements MouseListener,ActionListener,MouseMotionListener { Button lines,ovals,rect,free; int ch; int x,y,x2,y2,k; public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { x=e.getX(); y=e.getY();

} public void mouseReleased(MouseEvent e) { x2=e.getX(); y2=e.getY(); repaint(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) {if(k==1){ x2=e.getX(); y2=e.getY(); repaint();} } public void init() { lines=new Button("line"); ovals=new Button("oval"); rect =new Button("rect"); free=new Button("free hand"); add(lines);add(ovals);add(rect);add(free); lines.addActionListener(this); ovals.addActionListener(this); rect.addActionListener(this); free.addActionListener(this); addMouseListener(this); addMouseMotionListener(this); } public void actionPerformed(ActionEvent ki) { if(ki.getSource()==lines) { ch=1; k=0;} else if(ki.getSource()==ovals) { ch=2; k=0;} else if(ki.getSource()==rect) {ch=3; k=0;} else if(ki.getSource()==free) { ch=4; k=1;} } public void paint(Graphics g) { switch (ch) { case 1:g.drawLine(x,y,x2,y2); break;

case 2:g.drawOval(x,y,(x2-x),(y2-y)); break; case 3:g.drawRect(x,y,(x2-x),(y2-y)); break; case 4:repaint(); break; } } /*public void update(Graphics g) { paint(g); }*/ }