Compiled By: Bharath Annamaneni & Hari Vardhan Yerramsetty For
Compiled By: Bharath Annamaneni & Hari Vardhan Yerramsetty For
com
JNTU WORLD
Week1 :
www.jntuworld.com
2
www.jntuworld.co m
a) Write a Java program that prints all real solutions to the quadratic equation ax + bx + c = 0. Read in a, b, c 2 and use the quadratic formula. If the discriminant b -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 InputStreamReader(System.in)); int a=Integer.parseInt(br.readLin e()); int BufferedReader(new
c=Integer.parseInt(br.readLin e()); 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"); }
www.jntuworld.com
is
no
JNTU WORLD
}
www.jntuworld.com
www.jntuworld.co m
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
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
www.jntuworld.com
JNTU WORLD
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(" } } } } ");
www.jntuworld.com
b) Write a Java program to multiply two given matrices. import java.lang.*; import java.io.*; class arraymul
JNTU WORLD
{
www.jntuworld.com
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()); } }
JNTU WORLD
} 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]); } } } } } }.
www.jntuworld.com
c) Write a Java Program that reads a line of integers, and then displays each integer, 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
JNTU WORLD
{
www.jntuworld.com
www.jntuworld.co m
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 not.
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) {
JNTU WORLD
www.jntuworld.com
6
JNTU WORLD
c+ +; i+ +; p--; } if(c==len/2) { System.out.println("palin drom"); } else {
www.jntuworld.com
www.jntuworld.co m
if(s.charAt [i]==s.charAt(p))
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");
JNTU WORLD
www.jntuworld.com
7
JNTU WORLD
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; } } }
www.jntuworld.com
class Count {
JNTU WORLD
{ int i,c=0;
www.jntuworld.com
www.jntuworld.co m
Week 4 : a) Write a Java program that reads a file name from the user, then displays 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 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());
JNTU WORLD
www.jntuworld.com
9
JNTU WORLD
www.jntuworld.com
www.jntuworld.co m
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 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++;
JNTU WORLD
www.jntuworld.com
10
JNTU WORLD
System.out.println(c+t); } fr.close(); } }
www.jntuworld.com
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);
11
JNTU WORLD
System.out.println("total lines \n" +i ); f.close(); } catch(Exception) System.out.println("err"+e); } } }
www.jntuworld.com
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; }
12
JNTU WORLD
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);
www.jntuworld.com
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()); } }
13
JNTU WORLD
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) {
www.jntuworld.com
14
JNTU WORLD
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
www.jntuworld.com
15
JNTU WORLD
(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 {
www.jntuworld.com
16
JNTU WORLD
{ String s; BufferedReader br=new
www.jntuworld.com
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) {
17
JNTU WORLD
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') {
www.jntuworld.com
18
JNTU WORLD
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
www.jntuworld.com
19
JNTU WORLD
{ public static void main(String args[]) { String str; char postfix[]=new char[25]; float number[]=new float[25]; int j=0; try{
www.jntuworld.com
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));
20
JNTU WORLD
} }
www.jntuworld.com
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 its 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() {
21
JNTU WORLD
Container con=getContentPane(); con.setLayout(new BorderLayout());
www.jntuworld.com
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);
22
JNTU WORLD
} } }
www.jntuworld.com
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 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 :");
23
JNTU WORLD
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); }
www.jntuworld.com
24
JNTU WORLD
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)
www.jntuworld.com
{ JOptionPane.showMessageDialog(null,e ); }
25
JNTU WORLD
} }
www.jntuworld.com
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,MouseMotionListener { String msg=""; int x=0,y=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { x=1 0; y=20; msg="mouse clicked"; repaint(); } public void mouseEntered(MouseEvent me) { x=10; y=20;
26
JNTU WORLD
msg="mouse entered"; repaint(); }
www.jntuworld.com
public void mouseExited(MouseEvent me) { x=1 0; 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();
27
JNTU WORLD
}
www.jntuworld.com
www.jntuworld.co m
public void mouseMoved(MouseEvent me) { showStatus("moving +","+me.getY()); } public void paint(Graphics g) { g.drawString(msg,x,y); } } mouse at"+me.getX()
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.
class A Thread {
extends
synchronized public void run() { tr y { while(tru e) { sleep(1 0); System.out.println("good morning"); } } catch(Exceptio
JNTU n e) WORLD
{ }
www.jntuworld.com
28
JNTU WORLD
} } class B extends Thread {
www.jntuworld.com
synchronized public void run() { try { while(true) { sleep(20); System.out.println("he llo"); } } catch(Exception e) { } } class C extends Thread { synchronized public void run() { try { while(true) { sleep(30); }
29
JNTU WORLD
www.jntuworld.com
www.jntuworld.co m
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 using the concept of inter thread communication.
JNTU WORLD
www.jntuworld.com
30
JNTU WORLD
int n; synchronized int get() { if(!valueSet)
www.jntuworld.com
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(value Set) try { wait(); } catch(InterruptedException e) { System.out.p rintln
31
JNTU WORLD
("\n Exception in put:"+e); } this.n=n; valueSet=tr ue;
www.jntuworld.com
www.jntuworld.co m
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(tru e) q.put(i+ +); } } class Consumer implements Runnable { Q q; Consumer(Q
JNTU WORLD q)
www.jntuworld.com
32
JNTU WORLD
{ this.q=q;
www.jntuworld.com
www.jntuworld.co m
new Thread(this,"Consumer").start(); } public void run() { while(tr ue) 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 ArithmeticException Display the exception in a message dialog box.
import java.awt.*;
JNTU WORLD
www.jntuworld.com
33
JNTU WORLD
import java.awt.event.*; import java.applet.*;
www.jntuworld.com
www.jntuworld.co m
/*<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(num 1); add(l2);
www.jntuworld.com
34
JNTU WORLD
{
www.jntuworld.com
www.jntuworld.co m
String arg=ae.getActionCommand(); if(arg.equals("DIV")) { String s1=num1.getText(); String s2=num2.getText(); int num1=Integer.parseInt(s 1); int
num2=Integer.parseInt(s 2); if(num2==0) { try { System.out.println(" "); } catch(Exception e) { System.out.println("ArithematicExce ption"+e); } msg="Aritheme tic"; repaint(); } else if((num1<0)||(num2<0)) { try { System.out.print
www.jntuworld.com
35
JNTU WORLD
} catch(Exception e)
www.jntuworld.com
{ System.out.println("NumberFor mat"+e); } msg="NumberFor mat"; 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 client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result 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).
36
JNTU WORLD
import java.io.*; public class server {
www.jntuworld.com
www.jntuworld.co m
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.read Line()); System.out.println("From Client : "+rad); area=Math.PI*rad*rad; result="Area is "+area; PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(resu lt); br.close(); ps.close(); s.close(); ss.close(); } } Client.java import java.net.*; import java.io.*; public class
www.jntuworld.com
37
JNTU WORLD
{
www.jntuworld.com
www.jntuworld.co m
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 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.
www.jntuworld.com
38
JNTU WORLD
import java.awt.event.*; import javax.swing.*;
www.jntuworld.com
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);
39
JNTU WORLD
setSize(400,400); setVisible(true); c.setBackground(Color.pink); }
www.jntuworld.com
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.
40
JNTU WORLD
import java.applet.*; import java.awt.*; import javax.swing.*;
www.jntuworld.com
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 such that each one of the
41
JNTU WORLD
www.jntuworld.com
classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that shows the number of sides in the given geometrical figures.
import javax.swing.*; abstract class Shape { public abstract void numberOfSides(); } class Trapezoid extends Shape { public void numberOfSides() { JOptionPane.showMessageDialog(null,"TRAPEZOID -- Number of sides in trapezoid is 4 (Of which two are parallel and with no angles)"); } } class Triangle extends Shape { public void numberOfSides() { JOptionPane.showMessageDialog(null,"TRIANGLE -- Number of sides in Triangle is 3 "); } } class Hexagon extends Shape { public void numberOfSides() { JOptionPane.showMessageDialog(null,"HEXAGON -- Number of sides in Hexagon is 6 "); }
42
JNTU WORLD
} class ShapeDemo {
www.jntuworld.com
public static void main(String[] args) { JOptionPane.showMessageDialog(null,"Some of the Geometrical figures are as follows " ); Trapezoid t=new Trapezoid(); Triangle tg=new Triangle(); Hexagon h=new Hexagon(); t.numberOfSides(); tg.numberOfSides(); h.numberOfSides(); } }
b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table. The elements are 43eparated by commas. Write a java program to display the table using Jtable component.
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import java.io.*; public class Table1 extends JFrame { int i=0; int j=0,k=0; Object data[][]=new Object[5][4]; Object list[][]=new Object[5][4];
43
JNTU WORLD
JButton save; JTable table1; FileInputStream fis; DataInputStream dis; public Table1() { String d= " "; Container con=getContentPane(); con.setLayout(new BorderLayout());
www.jntuworld.com
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) ");
44
JNTU WORLD
{
www.jntuworld.com
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); } }
45