You are on page 1of 43

WEEK 1

1) 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.

Procedure

 Read a, b, c values from Keyboard ( By using BufferedReader class. )


 Take the condition ((b*b)-(4*a*c)) >= 0 (since, positive)
Then u will find out the formula

Result1 = (-b + Math.sqrt(b*b-4*a*c)) / (2*a)

Result12= (-b - Math.sqrt(b*b-4*a*c)) / (2*a)

(since, sqrt( ) is method given in Math class)

 if the condition is failed (since, negative)


then you just print “ There are no Real Solutions”

Example:

 take a=1, b=5, c=2


(5*5-4*1*2) = 17 > 0 -------- Condition True

result1 = -5+Math.sqrt(17)/(2*1) = -0.5615

result2 = -5-Math.sqrt(17)/(2*1) = -4.5615

/*1.Quadratic Equation Program */


import java.io.*;
class QuadEqn
{
public static void main(String args[])throws Exception {
int a,b,c;
double d,e;
System.out.println("Enter the values of a,b,c");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=Integer.parseInt(br.readLine());
double d,e;
if((b*b-4*a*c)>=0)
{
d=(-b+Math.sqrt(b*b-4*a*c))/(2*a);
e=(-b-Math.sqrt(b*b-4*a*c))/(2*a);
System.out.println("Root="+d);
System.out.println("Root="+e);
}
else
{
System.out.println("Root are imaginary");
}
}
}

Q) The Fibonacci sequence is defined by the following rule. The first two values in the
sequence are 1 and 1. Every subsequent value 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.

Procedure:

Reading Data from the Keyboard.


Our programs are more interesting when the program's user can enter information from
the
keyboard. The keyboard produces an input stream of bytes called System.in, which is a
predefined
object available to all Java programs. This stream is normally processed by a chain of
other objects
each of which performs a particular task. The first of these objects is of type
InputStreamReader.
It chops the stream of bytes into a stream of 2-byte units, each of which represents a
character
encoded in Unicode. The next object, of type BufferedReader, collects these characters
and allows

them to be accessed as entire lines of text (as delineated by new line characters). This
entire chain of
objects can be constructed in a Java program by the single statement

BufferedReader keyboard = new BufferedReader(new


InputStreamReader(System.in));

that declares the variable keyboard to be an object of type BufferedReader, which gets its
input
from an object of type InputStreamReader, which gets its input from the object
System.in.
The classes BufferedReader and InputStreamReader are defined in the Java
Application
Programming Interface, or Java API and must be added (or imported) to any program
that uses
them. This is done by including the statement
import java.io.*;

Procedure:

→ Read n value from keyboard (By using BufferedReader class) in the main ().
→ Pass that value to the two functions called rec() and nonrec() defined in another
class say test
→ In rec() we will give a condition n==0 or n==1 then return 1.
Otherwise return rec(n-1)+rec(n-2)

→ Return these values to a variable (say rec1) declared in main ().


→ In nonrec() we will initialize 2 values to 1, and take a loop for adding and
interchanging values
Say f1=1, f2=1

And take a loop from i =3 to n.

f= f1+f2

f1=f2

f2=f

→ Then print the values of “f”.


Output

Enter value for n

The recursive function output is

1, 1, 2, 3, 5, 8

The non-recursive function output is

1, 1, 2, 3, 5, 8

2. The Fibonacci sequence is defined by the following rule. The first two values in the
sequence are 1 and 1. Every subsequent value 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.*;

class Test {

int rec(int n)

if(n==0||n==1)

return 1;

else
return(rec(n-1)+rec(n-2));
}
void nonrec(int n)
{
int j,f1=1,f2=1,f;
System.out.println();
System.out.println("non recursive function output is ");
System.out.println(f1+","+f2+",");
for(j=3;j<=n;j++)
{
f=f1+f2;
f1=f2;
f2=f;
System.out.println(f+",");
}
}
}
class Fibonacci
{
public static void main(String args[])throws Exception {
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int rec,i,n;
System.out.println("Enter a value:");
n=Integer.parseInt(br.readLine());
Test t=new Test();
System.out.println("Recursive output is ..");
for(i=0;i<n;i++)
{
rec=t.rec(i);
System.out.print(rec+",");
}
t.nonrec(n);
}
}
***********************************************************************
*
WEEK 2

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

Procedure

 Read any positive Integer (say, n)


 Here we have to identify the prime numbers up to that integer using loop
statements
 Take a loop, i =1,2,….,n
Initialize a value to zero in that loop (say, p=0)

Take inner loop, j = 1, 2,………..,i

Then take condition i % j == 0

if the condition is true then increment p

After completing inner loop

Take the condition p == 2 it is true

Then print ‘i’ value

Then complete first loop.

Example

 Take n=5,
i=1, j=1 and let p=0

1%1 = = 0 ------- true then p++ = 1

1%2 = = 0 ------- false then loop completed, p = 1

p = = 2 ------- condition failed

i=2, j=1

2%1 = = 0 ------- true then p++ = 1

2%2 = = 0 ------- true then p++ = 2


2%3 = = 0 ------- false then loop completed, p = 2

p = = 2 ------- condition true

then print i --------- 2.

/* 3.Prime Number */
import java.io.*;
class Prime {
public static void main(String args[])throws Exception {
int count,n,i;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
for(n=1;n<=100;n++)
{
count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
System.out.println(n+"\t");
}
}//main
}//class

Output:
2 3 5 7 11 13 17 19

4) Write a java program to multiply two given Matrices

Procedure:

 Read m, n values from Keyboard ( size of matrix “a” )


 Read p, q values from Keyboard ( size of matrix “b” )
 Declare matrices a, b, c Matrices dynamically
 Take a condition n = = p (since, first matrix column size and second matrix row
size must be equal)
Then read the values for matrices a and b

 For matrix multiplication, we have to multiply ‘a’ matrix row values to ‘b’ matrix
column values
Example, a[0][0]*b[0][0] + a[0][1]*b[1][0]

……………………………

The logic we have to give here is

c[i][j] = a[i][k]*[k][j]

Here k is same for matrix ‘a’ column size and matrix ‘b’ row size.

 If the n = = p condition failed, Then print “ Matrix sizes not Matching”.

Arrays:

An array is a group of like-typed variables that are referred to by a common name.


Arrays
of any type can be created and may have one or more dimensions.

Example : int twoD[][] = new int[4][5];

By using array concept we are implementing the matrix multiplication.

Example

 m=2, n=2, p=2, q=2


 n = = p , 2 = = 2 ------------ condition True
Matrix ‘a’ values

2
3

Matrix ‘b’ values

Matrix ‘c’ values

(1*1) + (2*3) (1*2) + (2*4)

(3*1) + (4*3) (3*2) + (4*4)

Simply

7 10
15 22

/*.Matrix Multiplication*/
import java.io.*;
class Matrix
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int i,j,k,m,n,p,q;
System.out.println("Enter the size forA:m*n");
m=Integer.parseInt(br.readLine());
n=Integer.parseInt(br.readLine());
System.out.println("enter the size for b:p*q");
p=Integer.parseInt(br.readLine());
q=Integer.parseInt(br.readLine());
int a[][]=new int[m][n];
int b[][]=new int[p][q];
int c[][]=new int[m][q];
if(n==p)
{
System.out.println("enter the values of matrix a:m*n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j]=Integer.parseInt(br.readLine());
System.out.println("enter the values of matrix b:p*q");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
b[i][j]=Integer.parseInt(br.readLine());
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
System.out.println("The resultant matrix c is:"+"\t");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.println(c[i][j]+" ");
}
}
}
else
System.out.println("Matrix multiplication is not possible...");
}
}

5. Write a Java Program that reads a line of integers, and then displays each integer, and

the sum of all the integers (Use StringTokenizer classof java.util)

The processing of data often consists of parsing a formatted input data (or string). The string tokenizer class
allows an application to break a string into tokens. The discrete parts of a string are called tokens. The
StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do
they recognize and skip comments. The set of delimiters (the characters that separate tokens) may be
specified either at creation time or on a per-token basis. StringTokenizer implements the
Enumeration interface. Therefore, given an input string, we can enumerate the individual tokens
contained in it using StringTokenizer. The default delimiters are whitespace characters: space, tab,
newline, and carriage return. Other than default delimiters, each character in the delimiters string is
considered a valid delimiter.
A StringTokenizer object internally maintains a current position within the string to be tokenized.
Some operations advance this current position past the characters processed. A token is returned by taking a
substring of the string that was used to create the StringTokenizer object. The following is one
example of the use of the tokenizer. The code:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
prints the following output: (Here, space is the default delimiter)
this
is
a
test
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code.
StringTokenizer constructors are:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)

Program
import java.util.StringTokenizer;
import java.io.*;
class StringTokenizerDemo
{
public static void main(String[] args) throws IOException
{
BufferedReader kb = new
BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string of digits: ");
String str = kb.readLine();
StringTokenizer st = new StringTokenizer(str);
int a, sum = 0;
String s;
while (st.hasMoreTokens())
{
s = st.nextToken();
a = Integer.parseInt(s);
sum = sum + a;
System.out.println(a);
}
System.out.println("Sum of these integers = " + sum); }
}
This program prints the following output:
Enter a string of digits: 45 100 750 5
45
100
750
5
Sum of these integers = 900

***********************************************************************
*

WEEK 3

6.Write a java program that checks whether the given String is a Palindrome or not

( ex, MADAM is a palindrome)

Procedure

 Read a String from Keyboard (say, s1)


 Declare another String (Say s2)
 Then we have to reverse that String
Take a loop from last character index number to first character index number

(Since, s1.length ( )-1 to 0, and length () is a method used for finding String
length)
use charAT( ) to take individual characters from a String and store the Received
Characters in another String(say, s2)

 Compare both Strings by using equals( ) method (since, it is a method given in


String class)
s1.equals(s2)

if this condition is true then print

“ The given String is Palindrome “

otherwise “ The given String is not Palindrome “

Example

 s1 = MADAM
M ---------- s1.length( )-1

A -

D -

A -

M ---------- 0

 Then s2 = MADAM
 s1.equals(s2) condition true
Then print “ The given String is Palindrome ”.

/*4.String Palindrome or not */


import java.io.*;
class StrPalin
{
public static void main(String args[])throws Exception
{
System.out.println("Enter a string ..");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String s1=br.readLine();
String s2=new String();
for(int i=s1.length()-1;i>=0;i--)
{
s2=s2+s1.charAt(i);
}
if(s1.equals(s2))
System.out.println("given string is palindrome");
else
System.out.println("given string is not palindrome");
}}

7) Write a java program for sorting a given list of names in ascending order.

Procedure

→ Take a String array with some five names initialization.


→ Take 2 loops
First loop from 0 to arr.length,

Second loop from i+1 to arr.length

In the inner loop take a condition by using compareTo() of a String class

arr[j].compareTo(arr[i]<0)

Then take interchanging like

T=arr[i]

arr[i]=arr[j]

arr[j]=t

→ After completing inner loop then print arr[i]

Output

ant
ass

bos

hai

how

/sorting a given list of names in ascending order.*/

class StrAscend

String a[]={"bos","how","hai","ant","ass"};

public static void main(String args[])

int s=a.length;

String t=NULL;

for(int i=0;i<s;i++)

for(int j=i+1;j<s;i++)

if(a[j].compareTo(a[i]<0))

t=a[i];

a[i]=a[j];

a[j]=t;

}
for(int i=0;i<s;i++)

System.out.println(a[i]);

8. Write a java program to make frequency count of words in a given text.

NOT COMPLETED

***********************************************************************
*

WEEK 4

9. Write a java program that reads on 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 the file and the length of the file in bytes.

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

NOT COMPLETED

Software/Hardware Requirements:

S/W: JDK1.5(JAVA), Office XP, Windows NT Server with Service Pack

H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MB RAM
ALGORITHM:

1. Start the program, import the packages.

2. create an object of ‘fi’ using fileinputstream class

3. compute count=0

4. repeate ‘4’ until file is empty

5. if the new line is arrived then

printf counter,count++

6.Stop the program

Test Data:

Valid Data Set: line no:1import java.util.*;

line no:2class p14

line no:3{

line no:4public static void main(String args[])

line no:5{

Invalid Data Set: Not applicable

Limiting Data Sets: Integer Range (-32768 to 32767)


Results for different Data Sets

line no:1import java.util.*;

line no:2class p14

line no:3{

line no:4public static void main(String args[])

line no:5{

line no:6int s=0;

line no:7StringTokenizer token=new StringTokenizer(args[0],",");

line no:8while(token.hasMoreTokens())

line no:9s=s+Integer.parseInt(token.nextToken());

line no:10System.out.println(s);

line no:11}

line no:12}
line no:13 line no:14?

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

ALGORITHM:
1) Start the program, import the packages.

2) create an object of ‘fi’ using fileinputstream class

3) compute count=0,word=0,line=1,space=0

4) repeate ‘4’ until file is empty

5) if fi.read() equal to new line then

line++

else

fi.read() equal to space then

word++

else

char++

6) print word,line,char
7) Stop the program

8) Start the program, import the packages.

9) create an object of ‘fi’ using fileinputstream class

10) compute count=0,word=0,line=1,space=0

11) repeate ‘4’ until file is empty

12) if fi.read() equal to new line then


line++

else

fi.read() equal to space then

word++

else

char++

13) print word,line,char

14) Stop the program

******************************************************************************

WEEK 5
12. Write a java program that :

a)Implement Stack ADT b)converts infix expression into postfix form. c). Evaluate the
postfix expression .

******************************************************************************

WEEK 6

13. Develop an applet that displays a simple message.

Procedure

 To display a simple message in an Applet, we have to use


Graphics class object (say, g) in the paint()

And use syntax as

g.drawString (“text”, x-coordinate, y-coordinate)

 drawString( ) is a method given in java.awt package.

Example

 g.drawString(“welcome to Applet Programming”,130,200)


/*Simple Applet program with Message*/

import java.awt.*;
import java.applet.*;
/*
<applet code="MyAppletTest" width=500 height=300>
</applet>
*/

public class MyAppletTest extends Applet {


public void paint(Graphics g)
{
g.drawString("Welcome To Applet
Programming..",10,20);
}
}

14. 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.

NOT COMPLETED

******************************************************************************

WEEK 7

15. Write a java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +-*% operations. And a text field to display the result.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Calculator.class" width=200 height=200>
</applet>
*/
public class Calculator extends Applet
implements ActionListener
{
TextField t1;
Button[] b=new Button[20];
Panel p1,p2,p3,p4,p5;
String fn="",sn="",str="",s="";String oper="";
public void init()
{
p1=new Panel();
t1=new TextField(20);
setLayout(new BorderLayout());
p1.add(t1);
add(p1,"North");
p2=new Panel();
add(p2);
p2.setLayout(new BorderLayout(5,5));
p3=new Panel();
p2.add(p3);
p3.setLayout(new GridLayout(3,3,5,5));
for(int i=0;i<9;i++)
{
b[i]=new Button(i+1+" ");
p3.add(b[i]);
}
p4=new Panel();
p4.setLayout(new GridLayout(3,1,5,5));
p4.add(b[9]=new Button("C"));
p4.add(b[10]=new Button("/"));
p4.add(b[11]=new Button("*"));
p2.add(p4,"East");
p5=new Panel();
p5.setLayout(new GridLayout(1,4,5,5));
p5.add(b[12]=new Button("0"));
p5.add(b[13]=new Button("="));
p5.add(b[14]=new Button("+"));
p5.add(b[15]=new Button("-"));
p2.add(p5,"South");
for(int i=0;i<=15;i++)
{
b[i].addActionListener(this);
}
setBackground(Color.cyan);
setForeground(Color.black);
}
public void actionPerformed(ActionEvent ae)
{
str=ae.getActionCommand();
if(str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/"))
{
oper=str;
fn=t1.getText();
s="";
}
else if(str.equals("="))
{
sn=t1.getText();
double x=Double.parseDouble(fn);
double y=Double.parseDouble(sn);
if(oper.equals("+"))
t1.setText(" "+(x+y));
if(oper.equals("-"))
t1.setText(" "+(x-y));
if(oper.equals("/"))
t1.setText(" "+(x/y));
if(oper.equals("*"))
t1.setText(" "+(x*y));
}
else if(str.equals("C"))
{
t1.setText("");
s="";
}
else
{
s=s+ae.getActionCommand().trim();
t1.setText(s);
}
showStatus("CALCULATOR");
}
}

******************************************************************************

WEEK 8

16. Write a java program for handling mouse and key events.
/*Demonstrate the Mouse Event Handlers.*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle Mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse Clicked.";
repaint();
}
// Handle Mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse Entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle Button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle Mouse Dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

******************************************************************************

WEEK 9

17. 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 third thread
displays “Welcome” every three seconds.
NOT COMPLETED

18. Write a java program that correctly implements producer consumer problem using
the concept of inter thread communication.

******************************************************************************

WEEK 10

19. Write a java program that creates user interface to perform integer divisions. The
user enters two numbers in a text fields, Num1 & Num2. The division of Num1 & 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 ArithemeticExpception Display the exception in a message
dialogbox.

Procedure:
1. Create three Textfield objects and one Button
Ex; Label l1=new Label("enter num1");
Textfield T1 =new TextField(5);
Button b1=new Button("divide");

2. Add these object to the frame window.


3. Define two user define classes which extends Dialog class.
4. Override the actionPerformed() method to receive two numbers and divide
number1 by number2. this entire code should be written in side the try- catch
block
5. In Arithmetic Exception catch block create Dialog class object to display its
exception in the message dialog box.
6. In NumberFormatException catch block create Dialog class object to display its
exception in the message dialog box
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class NumberDemo1 extends Frame implements ActionListener
{
Panel p1,p2,p3;
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1;
NumberDemo1()
{
setLayout(new GridLayout(7,1));
l1=new Label("enter num1");
t1=new TextField(5);
l2=new Label("enter num2");
t2=new TextField(5);
l3=new Label("after divide is:");
t3=new TextField(5);
b1=new Button("divide");
b1.addActionListener(this);
p1=new Panel();
p2=new Panel();
p3=new Panel();
p1.add(l1);
p1.add(t1);
p2.add(l2);
p2.add(t2);
p3.add(t3);
p3.add(b1);
add(p1);
add(p2);
add(p3);
}

public void actionPerformed(ActionEvent ae)


{
int num1,num2,num3=0;
try
{
num1=Integer.parseInt(t1.getText());
num2=Integer.parseInt(t2.getText());
if(ae.getSource()==b1)
{
num3=num1/num2;
}
t3.setText(" "+num3);
}
catch(NumberFormatException ne)
{
System.out.println("from catch "+this);
new MessageDialog1(this,"dialog demo");
}
catch(ArithmeticException e)
{
System.out.println("from catch "+this);
new MessageDialog2(this,"dialog demo");
}
System.out.print(num3);
}
public static void main(String args[])
{
NumberDemo1 d=new NumberDemo1();
d.setSize(300,300);
d.setVisible(true);
}
}
class MessageDialog1 extends Dialog
{
MessageDialog1(Frame parent,String title)
{
super(parent,title,false);
setVisible(true);
setSize(200,200);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
dispose();
}
});
}
public void paint(Graphics g)
{
g.drawString("Numberformat Exception ",30,100);
}
}
class MessageDialog2 extends Dialog
{
MessageDialog2(Frame parent,String title)
{
super(parent,title,false);
setVisible(true);
setSize(200,200);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
dispose();
}
}
);
}
public void paint(Graphics g)
{
g.drawString("Arithmetic Exception ",30,100);
}
}
******************************************************************************

WEEK 11

20. Write a java program that simulates a traffic lights. 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.

Procedure:
1. Define a user define class which extends Applet class and
implements Item Listener interface.
Ex: public class TrafficDemo extends Applet implements
ItemListener
2. Create Checkbox group as follows
Ex: CheckboxGroup cbg;
3. Create three checkbox objects with same checkbox group.
Ex: Chechbox cb1=new Checkbox("red",cbg,false);
Chechbox cb2=new Checkbox("yellow",cbg,false);
Chechbox cb3=new Checkbox("greed”,cbg,false);
4. Override the itemStateChanged() method to know which radio
button was pressed and accordingly return which color to be set
to circle
5. Override the paint() method to create three circles one after the
other and set three different colors.
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="TrafficDemo" height="300" width="300">
</applet>
*/
public class TrafficDemo extends Applet implements ItemListener
{
Checkbox cb1,cb2,cb3;
String str=" ";
CheckboxGroup cbg;
Color c;
public void init()
{
setBackground(Color.red);
cbg=new CheckboxGroup();
cb1=new Checkbox("red",cbg,false);
add(cb1);
cb1.addItemListener(this);
setBackground(Color.yellow);
cb2=new Checkbox("yellow",cbg,true);
add(cb2);
cb2.addItemListener(this);
setBackground(Color.green);
cb3=new Checkbox("green",cbg,true);
add(cb3);
cb3.addItemListener(this);
setBackground(Color.white);
}
public void itemStateChanged(ItemEvent ie)
{
str=cbg.getSelectedCheckbox().getLabel();
if(str.equalsIgnoreCase("red"))
c=new Color(255,0,0);
else if(str.equalsIgnoreCase("green"))
c=new Color(0,255,0);
else if(str.equals("yellow"))
c=new Color(0,0,255);
repaint();
public void paint(Graphics g)
{
g.drawString(str,30,100);
g.setColor(c);
g.drawOval(150,100,60,60);
g.drawOval(150,170,60,60);
g.drawOval(150,250,60,60);
if(str.equals("red"))
{
g.fillOval(150,100,60,60);
}
else if(str.equals("yellow"))
{
g.setColor(Color.yellow);
g.fillOval(150,170,60,60);
}
else if(str.equals("green"))
{
g.fillOval(150,250,60,60);
}
System.out.println(str);
}
}

21. Write a java program that allows the user to draw lines, rectangle and ovals.

NOT COMPLETED

******************************************************************************

WEEK 12

22.Write a java program to create an abstract class named shape that contains an empty
method named numberOfSides(). Provides three classes named Trapezoid, Triangle and
Hexagon such that each one of the classess 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.

Procedure:
1.Define the class Shape with abstract method numberOfSides().
Ex: abstract void numberOdSides();
2. Define another class Triangle which extends Shape class and overrides
abstract method define in the Shape class.
3. Define third class Trepezoid which extends Shape class and overrides
abstract
method define in the Shape class.
4. Define fourth class Hexagon which extends Shape class and overrides
abstract
method define in the Shape class.

Example:
class Shape
{
Shape()
{
}
abstract void numberOdSides();
}
class Triangle extends Shape
{
void numberOdSides()
{
System.out.println("No of sides are three");
}
}
class Trapezoid extends Shape
{
void numberOdSides()
{
System.out.println("No of sides are four");
}
}

class Hexagon extends Shpae


{

void numberOdSides()
{
System.out.println("No of sides are six");
}
}
class ShapeDemo
{
public static void main(String args[])
{

Shape ref;
Triangle t=new Triangle();
Hexagon h=new Hexagon();
Trapezoid tp=new Trapezoid();

ref=t;
ref.numberOfSides();
ref=h;
ref.numberOfSides();
ref=tp;
ref.numberOfSides();
}
}

23. Suppose that table named Table.txt is stored in a test 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.

Procedure:
1. Read the file table.txt using File Reader.
Ex: BufferReader br=new BufferReader(new FileReader(table.txt))
2. Separate each attribute of the table using StringTokenizer.
Ex: StringTokenizer st1=new StringTokenizer(str,", ");
3. Store column heads in single dimensional array variable.
Ex: heading[i]=st1.nextToken();
4. Store data of the table in the two dimensional array variable.
Ex: data[i][j]=st2.nextToken()
5. Create a JTable object with two parameters data and col variables
Ex: JTable table=new JTable(data,heading)

PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
/*
<applet code="JTableDemo" width="300" height="300">
</applet>
*/
public class JTableDemo extends JApplet
{
public void init()
{
try
{
/* Creating an object of Buffer Reader class for reading the table.txt
file*/
BufferedReader br=new BufferedReader(new FileReader("table.txt"));
String heading[]=new String[3];
String str=br.readLine();
StringTokenizer st1=new StringTokenizer(str,", ");
int i=0;
while(st1.hasMoreTokens())
{
heading[i]=st1.nextToken();
i++;
}
String data[][]=new String[10][3];
i=1;
int j;
while((str=br.readLine())!=null)
{
j=0;
System.out.println(str);
StringTokenizer st2=new StringTokenizer(str,", ");

while(st2.hasMoreTokens())
{
data[i][j]=st2.nextToken();
j++;
}
i++;

}
JTable table=new JTable(data,heading);
JScrollPane jsp=new JScrollPane(table);
add(jsp);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

******************************************************************************

You might also like