Thursday 29 October 2015

SIMPLE JAVA PROGRAMS TO MY DEAR STUDENTS

Ex.No:1
Date:
Displaying Individual Digit
AIM:
To write a program to print the individual digit of given 3 – digit number
ALGORITHM:
STEP 1: Get three digit number
STEP 2: Store three digit number to variable no
STEP 3: Assign digit = no%10
STEP 4: Display digit
STEP 5: Assign no = no / 10
STEP 6: Repeat step 2,3,4 until no != 0
PROGRAM:
import java.io.*;
class exno1
{
public static void main(String args[])
{
int no=0,digit=0;
DataInputStream din = new DataInputStream(System.in);
try
{
System.out.println("Enter a number");
no =Integer.parseInt( din.readLine());
System.out.print("Individual Digits are :");
do
{
digit=no%10;
System.out.print(digit);
no=no/10;
}while(no!=0);
}
catch(IOException e)
{
System.out.println("Error");
}
}
}
OUTPUT:
RESULT:
Thus the program Displaying Individual digit has been executed and verified successfully.
Ex.No:2
Date:
Large and Equal Relationship Between Two Numbers
AIM:
To write a program that asks the user to enter two integers, obtain the numbers from the user, and then prints the larger number followed by the words “is larger”. If the numbers are equal , print the message “Theses numbers are equal”
ALGORITHM:
STEP 1: Get two numbers
STEP 2: Store the first number to variable a and second number to variable b STEP 2: Compare if a is equal to b then print “These numbers are equal”
STEP 3: Compare if a is greater than b then display value of a followed by a message
“is larger”
STEP 2: Otherwise , display value of b followed by a message “is larger”
PROGRAM:
import java.io.*;
class exno2
{
public static void main(String args[])
{
int a=0,b=0;
DataInputStream din = new DataInputStream(System.in);
try
{
System.out.println("Enter First number");
a =Integer.parseInt( din.readLine());
System.out.println("Enter Second number");
b =Integer.parseInt( din.readLine());
if(a==b)
System.out.println("These Nubers are Equal");
else if(a>b)
System.out.println(a + " is larger");
else
System.out.println(b + " is larger");
}
catch(IOException e)
{
System.out.println("Error");
}
}
}
OUTPUT:
RESULT:
Thus the program Large and Equal Relationship Between Two Numbers has been executed and verified successfully.
Ex.No:3
Date:
Armstrong Number
AIM:
To write a program to find three digit Armstrong numbers
ALGORITHM:
STEP 1: Set the for loop i=100
STEP 2: Set no = I, sum =0
STEP 3:Assign digit = no % 10
STEP 4:Calculate sum = sum + (digit * digit * digit)
STEP 5:Assign no = no / 10
STEP 6:Repeat thru step 3 until no != 0
STEP 7:If sum is equal to i then print I
STEP 8:Increment I = I +1
STEP 9:Repeat thru steps 2 until I <1000
PROGRAM:
import java.io.*;
class exno3
{
public static void main(String args[])
{
int no,digit,sum,i;
System.out.println("The ArmStrong Numbers are");
for(i=100;i<1000;i++)
{
no=i;
sum=0;
do
{
digit=no%10;
sum=sum+(digit*digit*digit);
no=no/10;
} while(no!=0);
if(sum==i)
System.out.println(sum);
}
}
}
OUTPUT:
RESULT:
Thus the program Armstrong number has been executed and verified successfully
Ex.No:4
Date:
Largest and Smallest Number
AIM:
To write a program to read n numbers and find smallest and largest numbers
ALGORITHM:
STEP 1: Get the number and store to variable n
STEP 2: Set the for loop I = 0
STEP 3: Get the number and store to array variable value[i]
STEP 4:Increment I = I +1
STEP 5:Repeat thru step 3 until I < n
STEP 6:Set max = value[0],min= value[0]
STEP 7: Set the for loop I = 0
STEP 8:if min > value[i] then update min = value[i]
STEP 9:if max < value[i] then update max = value[i]
STEP 10:Increment I = I +1
STEP 11:Repeat thru step 8 until i<n
STEP 12:Display max and min
PROGRAM:
import java.io.*;
class exno4
{
public static void main(String args[])
{
int max=0,min=0,i,n;
int value[] = new int[100];
DataInputStream din = new DataInputStream(System.in);
try
{
System.out.print("Enter the value of n :");
n =Integer.parseInt( din.readLine());
System.out.println("Enter the values of array one by one ");
for(i=0;i<n;i++)
value[i] =Integer.parseInt( din.readLine());
min=value[0];
max=value[0];
for(i=0;i<n;i++)
{
if(min >value[i])
min=value[i];
if(max<value[i])
max=value[i];
}
System.out.println("Largest Number is " + max);
System.out.println("Smallest Number is " + min);
}
catch(IOException e)
{
System.out.println("Error");
}
}
}
OUTPUT:
RESULT:
Thus the program Largest and Smallest Number has been executed and verified successfully
Ex.No:5
Date:
String Operations
AIM:
To write a program in java to create a string object . Initialize this object with your name. Find the length of your name using the appropriate string method. Find whether the character „a‟ is in your name or not; if yes find the number of times „a‟ appears in your name. Print the locations of occurrences of „a‟
ALGORITHM:
STEP 1: Create String class object to initialise a string
STEP 2: Call length() method to display length of the given string
STEP 3: Set I =0,count=0
STEP 4:Find position of „a‟ using indexOf() method and store to a variable pos.
STEP 5:If pos != -1 then print position of „a‟ . otherwise go to step 9
STEP 6:Incremnet count =count +1
STEP 7:Set I = pos+ 1
STEP 8:Go to Step 4
STEP 9:Display Total occurrence of „a‟
PROGRAM:
import java.io.*;
class exno5
{
public static void main(String args[])
{
String name = new String ("P.K");
int l,count=0,i,pos;
l=name.length();
System.out.println("Given String is " + name);
System.out.println("Total Length is " +l);
i=0;
for(;;)
{
pos= name.indexOf("a",i);
if(pos !=-1)
{
System.out.println("'a' appears in position no " + pos);
count++;
i=pos+1;
}
else
break;
}
System.out.println("Total Occurence of 'a' is "+count);
}
}
OUTPUT:
RESULT:
Thus the program String Operations has been executed and verified successfully
Ex.No: 6(Part –B)
Date:
StringBuffer Class Operations
AIM:
(a)To create a string buffer object and illustrate how to append character. Display the capacity and length of the string buffer
(b)To create a string buffer object and illustrate how to insert characters at the beginning.
(c)To create a string buffer object and illustrate the operations of the append and reverse methods
ALGORITHM:
STEP 1: Create String Buffer class object „s‟
STEP 2: Call capacity() method to display capacity of object „s‟
STEP 3: Create String Buffer class object s1 to display initial capacity
STEP 4: Create String Buffer class object s2 with initial string „nlp‟
STEP 5: Call capacity() and length() method to display capacity and length of object s2
STEP 6: Call insert() method to insert string „hello‟ at beginning position of object s2
STEP 7: Call append() method to add string „welcome‟ to object s2
STEP 8: Call reverse() method to reverse the string of object s2
PROGRAM:
class stringbuffer
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer();
System.out.println("Object S Capacity :"+ s.capacity());
StringBuffer s1 = new StringBuffer(5);
System.out.println("Object S1 Capacity :"+ s1.capacity());
StringBuffer s2 = new StringBuffer("nlp");
System.out.println("Object S2 Capacity :"+s2.capacity());
System.out.println("Object S2 Length :"+s2.length());
s2.insert(0,"hello");
System.out.println("After Insert At Beginning :"+s2);
s2.append("welcome");
System.out.println("After Append :"+s2);
s2.reverse();
System.out.println("After Reversing :"+s2);
}
}
OUTPUT:
RESULT:
Thus the program StringBuffer Class Operations has been executed and verified successfully
Ex.No:7(Part –B)
Date:
Vector
AIM:
To write a program that accepts a shopping list of four items from the command line and stores them in a vector. Write a menu based program to perform the following operations using vector
1.To add an item at a specific locations in the list
2.to delete an item in the list
3.To print the contents of the vector
4.To delete all elements
5.To add an item at the end of the vector
ALGORITHM:
STEP 1: Create Vector object „v‟
STEP 2: Call addElement() to add elements to a vector
STEP 3: Call insertElementAt() to insert a particular element at particular location
STEP 4: Call removeElementAt() to remove the element at the specified location
STEP 5: Call removeAllElements() to empty the vector
STEP 6: To display vector elements , call elements() method using enumerator interface
STEP 7: After inserting or removing, display vector elements
PROGRAM:
import java.util.*;
import java.io.*;
public class vector
{
public static void main(String args[])
{
int opt,i;
Vector v = new Vector();
try
{
DataInputStream din = new DataInputStream(System.in);
l1: for(;;)
{
System.out.println("1.Append");
System.out.println("2.Insert");
System.out.println("3.Delete");
System.out.println("4.Delete All");
System.out.println("5.Print");
System.out.println("6.Exit");
System.out.print("Enter Your Choice :");
opt=Integer.parseInt(din.readLine());
switch(opt)
{
case 1 : for(i=0;i<args.length;i++)
v.addElement(args[i]);
break;
case 2 : v.insertElementAt("pen",2);
break;
case 3 : v.removeElementAt(2);
break;
case 4 : v.removeAllElements();
break;
case 5 : Enumeration e = v.elements();
while( e.hasMoreElements())
System.out.println(e.nextElement());
break;
case 6 : break l1;
}
}
}
catch(IOException e)
{
System.out.println("Error");
}
}
}
OUTPUT:
RESULT:
Thus the program Vector has been executed and verified successfully
Ex.No:8
Date:
Implementation of Student Class
AIM:
To write a program to display total marks of 5 students using student class.Given the following attributes :regno(int),name(string),marks in three subjects(intger array),total(int)
ALGORITHM:
STEP 1: Create Student class array object „s‟
STEP 2: Set for loop j=0
STEP 3: Call s[j].read() to get regno,name,marks of three subjects
STEP 4: Calculate total of three subjects
STEP 5: Increment j=j+1
STEP 6: Repeat steps 3,4,5 until j<5
STEP 7: Set for loop j=0
STEP 8: Call s[j].print() to show details of regno,name,marks of three subjects and total
STEP 9: Increment j=j+1
STEP 10: Repeat steps 8,9 until j<5
PROGRAM:
import java.io.*;
class student
{
int regno;
String name;
int marks[];
int total;
student()
{
total=0;
marks = new int[3];
}
void read()
{
try
{
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter Register no:");
regno =Integer.parseInt(din.readLine());
System.out.print("Enter Name:");
name =din.readLine();
for(int i=0;i<3;i++)
{
System.out.print("Enter Mark:");
marks[i]=Integer.parseInt(din.readLine());
total = total+marks[i];
}
}
catch(IOException e)
{
System.out.println("Error");
}
}
void print()
{
System.out.println("----------------------------------------");
System.out.println("Register No:"+regno);
System.out.println("Name:"+name);
System.out.print("Marks:");
System.out.println(marks[0]+" "+marks[1]+" "+marks[2]);
System.out.println("Total:"+total);
}
}
class studentdemo
{
public static void main(String args[])
{
student s[] = new student[5];
for(int j=0;j<5;j++)
{
s[j]=new student();
s[j].read();
}
for(int j=0;j<5;j++)
s[j].print();
}
}
OUTPUT:
RESULT:
Thus the program Implementation of student class has been executed and verified successfully
Ex.No:9(Part-B)
Date:
Complex Number
AIM:
To create a class to represent complex number operations
ALGORITHM:
STEP 1: Create a complex class which consists of constructors with the following arguments:
i) Default
ii)Taking 2 arguments real and imaginary value
STEP 2: Define add(). Sub() and print() method to add two complex numbers , subtract
two complex numbers and print the result
STEP 3: In the main class, create object c1,c2,c3 for complex class and pass two complex
number values to two argument constructor through c1 and c2 object
STEP 4: Call c3.add(c1,c2) method to add two complex numbers STEP 5: Call c3.print() method to display addition result
STEP 6: Call c3.sub(c1,c2) method to subtract two complex numbers
STEP 7: Call c3.print() method to display subtraction result
PROGRAM:
class complex
{
double rp,ip;
complex()
{
rp=0.0;
ip=0.0;
}
complex(double x,double y)
{
rp=x;
ip=y;
}
void add(complex c1,complex c2)
{
rp=c1.rp+c2.rp;
ip=c1.ip+c2.ip;
}
void sub(complex c1,complex c2)
{
rp=c1.rp-c2.rp;
ip=c1.ip-c2.ip;
}
void print()
{
System.out.println( "(" + rp + "," + ip +")" );
}
}
class complexdemo
{
public static void main(String args[])
{
complex c1 ,c2,c3;
c1=new complex(13,15);
c2=new complex(3.2,5.10);
c3=new complex();
System.out.print("Fitst Complex No:");
c1.print();
System.out.print("Second Complex No:");
c2.print();
System.out.print("Complex Addition:");
c3.add(c1,c2);
c3.print();
System.out.print("Complex Subtraction:");
c3.sub(c1,c2);
c3.print();
}
}
OUTPUT:
RESULT:
Thus the program Complex Number has been executed and verified successfully
Ex.No:10(Part-B)
Date:
Rectangle Class
AIM:
To create a class rectangle to get length, width, colour and find their area . Create two objects of rectangle and compare their area and colour . If both are same then display “Matching –Rectangles” .otherwise display Non-Matching Rectangles
ALGORITHM:
STEP 1: Create a Rectangle class which consists of area, length, width and colour fields
STEP 2: Define get_length() method to read length of a rectangle
STEP 3: Define get_width() method to read width of a rectangle
STEP 4: Define get_colour() method to read colour of a rectangle
STEP 5: Define find_area() method to find area of a rectangle
STEP 6: (i) Define compare() method to check whether the area and colour of two object is
matched or not
(ii) if matched the display “Matching – Rectangles” otherwise display “Non-Matching
Rectangles”
STEP 7: In the main class, create object r1,r2 for rectangle class and call appropriate methods
and show the result
PROGRAM:
import java.io.*;
class Rectangle
{
double area,length,width;
String colour;
void get_length()
{
try
{
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter Length:");
length = Double.parseDouble(din.readLine());
}
catch(IOException e)
{}
}
void get_width()
{
try
{
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter Width:");
width = Double.parseDouble(din.readLine());
}
catch(IOException e)
{}
}
void get_colour()
{
try
{
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter Colour:");
colour=din.readLine();
}
catch(IOException e)
{}
}
void find_area()
{
area = length * width;
}
void compare(Rectangle r2)
{
if( (area == r2.area) && (colour.equals(r2.colour)) )
System.out.print("Matching Rectangles");
else
System.out.print("Non-Matching Rectangles");
}
}
class rectdemo
{
public static void main(String args[])
{
Rectangle r1,r2;
r1=new Rectangle();
r2=new Rectangle();
r1.get_length();
r1.get_width();
r1.get_colour();
r1.find_area();
r2.get_length();
r2.get_width();
r2.get_colour();
r2.find_area();
r1.compare(r2);
}
}
RESULT:
Thus the program Rectangle Class has been executed and verified successfully
Ex.No:11(Part-B)
Date:
Implementation of Inheritance
AIM:
To write a program to create a player class. Inherit the classes cricket_player ,football_player and hockey_player from player class
ALGORITHM:
STEP 1: Create a player class which consists of name,dob and country and constructors with
the following arguments:
i) Default
ii)Taking 3 arguments name,dob and country
STEP 2: Create cricket_player class inherits player class which consists of tot_runs and
tot_wickets and constructors with the following arguments:
i)Taking 5 arguments name,dob and country,tot_runs,tot_wickets
STEP 3: Create football_player class inherits player class which consists of tot_goals and
constructors with the following arguments:
i)Taking 4 arguments name,dob and country,tot_goals
STEP 4: Create hockey_player class inherits player class which consists of position, tot_goals
and constructors with the following arguments:
i)Taking 5 arguments name, dob and country, position and tot_goals
STEP 5: Define display() method to show details of a player which overrides the base class
player
STEP 7: In the main class, create object for cricket_player ,foot_ball player and hockey_player
and call display() method to show the player details
PROGRAM:
class player
{
String name,country,dob;
player()
{
name="";
country="";
dob="";
}
player(String n,String d,String s)
{
name=n;
dob=d;
country=s;
}
void display()
{
System.out.println("Name:"+name);
System.out.println("Date of birth:"+dob);
System.out.println("Country:"+country);
}
}
class cricket_player extends player
{
int tot_runs,tot_wickets;
cricket_player(String n,String d,String c,int r,int w)
{
super(n,d,c);
tot_runs=r;
tot_wickets=w;
}
void display()
{
super.display();
System.out.println("Runs:"+tot_runs);
System.out.println("Wickets:"+tot_wickets);
System.out.println("------------------------------------------------------------------------");
}
}
class football_player extends player
{
int tot_goals;
football_player(String n,String d,String c,int g)
{
super(n,d,c);
tot_goals=g;
}
void display()
{
super.display();
System.out.println("Goals:"+tot_goals);
System.out.println("------------------------------------------------------------------------");
}
}
class hockey_player extends player
{
String position;
int tot_goals;
hockey_player(String n,String d,String c,String p,int g)
{
super(n,d,c);
position=p;
tot_goals=g;
}
void display()
{
super.display();
System.out.println("Position:"+position);
System.out.println("Goals:"+tot_goals);
System.out.println("------------------------------------------------------------------------");
}
}
class playerdemo extends player
{
public static void main(String args[])
{
cricket_player cp = new cricket_player("Sachin","12/12/1969","India",10000,500);
football_player fp = new football_player("Ronaldo","10/12/1969","Brazil",100);
hockey_player hp = new hockey_player("SandeepSingh","10/12/1970","India","Attacker",10);
cp.display();
fp.display();
hp.display();
}
}
OUTPUT:
RESULT:
Thus the program Implementation of Inheitance has been executed and verified successfully
Ex.No:12(Part-A)
Date:
Implementation of two Interfaces
AIM:
To write a program to implement two interfaces
ALGORITHM:
STEP 1: Create an interface Area and declare a method area()
STEP 2: Create an interface Display and declare a method print()
STEP 3: Create rect class that implements the interface Area,Display and define method area ()
to calculate area of a rectangle and call print() method to show the result
STEP 4: Create circle class that implements the interface Area,Display and define method area()
to calculate area of a circle and call print() method to show the result
STEP 5: In the main class, create object for rect , circle class and interface Area and assign rect
object to interface object and call area() method
PROGRAM:
interface Area
{
double pi = 3.14 ;
void area(double x,double y);
}
interface Display
{
void print(double a);
}
class rect implements Area,Display
{
public void area(double x,double y )
{
print(x*y);
}
public void print(double a)
{
System.out.println(a);
}
}
class circle implements Area,Display
{
public void area(double x,double y )
{
print(pi*x*x);
}
public void print(double a)
{
System.out.print(a);
}
}
class interfacedemo
{
public static void main(String args[])
{
rect r = new rect();
circle c = new circle();
Area a;
a=r;
System.out.print("Area of a Rectangle(5.5,2.6):");
a.area(5.5,2.6);
System.out.print("Area of a Circle(5.5):");
a=c;
a.area(5.5,5.5);
}
}
OUTPUT:
RESULT:
Thus the program Implementation of two Interfaces has been executed and verified successfully
Ex.No:13(Part-B)
Date:
Implementation of Bar Chart
AIM:
To write a program to implement bar chart using applets
ALGORITHM:
STEP 1: Create a class barchart which extends Applet super class
STEP 2: Define init() method to get subject names and marks using getParameter() method
STEP 3: Set for loop to draw bar chart and its labels using fillRect() method and drawString()
method
PROGRAM:
/* <applet code="barchart.class" height=300 width=350>
<param name ="totcol" value="4">
<param name = "c1" value = "78">
<param name = "c2" value = "85">
<param name = "c3" value = "98">
<param name = "c4" value = "56">
<param name = "lbl1" value = "Tamil">
<param name = "lbl2" value = "English">
<param name = "lbl3" value = "Maths">
<param name = "lbl4" value = "Physics"> </applet> */
import java.awt.*;
import java.applet.*;
public class barchart extends Applet
{
int n=0;
String label[];
int value[];
public void init(){
try{
n = Integer.parseInt(getParameter("totcol"));
label = new String[n];
value = new int[n];
label[0] = getParameter("lbl1");
label[1] = getParameter("lbl2");
label[2] = getParameter("lbl3");
label[3] = getParameter("lbl4");
value[0] = Integer.parseInt(getParameter("c1"));
value[1] = Integer.parseInt(getParameter("c2"));
value[2] = Integer.parseInt(getParameter("c3"));
value[3] = Integer.parseInt(getParameter("c4"));
} catch(Exception e) {}
}
public void paint(Graphics g)
{
for (int i=0;i<n ;i++ )
{
g.setColor(Color.red);
g.drawString(label[i],20,(i*50)+30);
g.setColor(Color.blue);
g.fillRect(70,(i*50)+10,value[i],40);
g.drawString(" " +value[i],value[i]+50,(i*50)+30);
}
}
}
OUTPUT:
RESULT:
Thus the program Implementation of Bar Chart has been executed and verified successfully
Ex.No:14(Part-B)
Date:
Implementation of package
AIM:
To write a program to implement package for book details giving book name, author name, price , year of publishing
ALGORITHM for book package:
STEP 1: Create a package named as book
STEP 2: Create a class Book in the book package which consists of constructors with the
following arguments
i)Taking three arguments book name, author name, price and year of publishing
STEP 3: Define display() method to show name,author name,price and year of publishing
ALGORITHM for bookdemo :
STEP 1: import book package
STEP 2: In the main class, create object for Book and pass arguments to constructors
STEP 3: Call display() method to display book details
PROCEDURE FOR CREATING PACKAGE
STEP 1:create a folder named as book under your own folder
STEP 2:double click to open book folder
STEP 3:open notepad and type source code for book package
STEP 4:save it as Book.java
STEP 5:compile Book.java [javac Book.java]
STEP 6:change to your folder
STEP 7:open notepad and type source code for bookdemo
STEP 8:save it as bookdemo.java
STEP 9:compile bookdemo.java [javac bookdemo.java]
STEP 4:run bookdemo [java bookdemo]
PROGRAM for book package:
package book;
public class Book
{
String name,author;
int yop;
double price;
public Book(String na,String au,double pr,int y)
{
name=na;
author=au;
price =pr;
yop=y;
}
public void display()
{
System.out.println("Name :"+name);
System.out.println("Author :"+author);
System.out.println("Price :"+price);
System.out.println("Year of Publishing :"+yop);
}
}
PROGRAM for bookdemo class :
import book.*;
public class bookdemo
{
public static void main(String args[])
{
Book b = new Book("Java Programming","AswinBala",245.89,2000);
b.display();
}
}
OUTPUT:
RESULT:
Thus the program Implementation of package has been executed and verified successfully
Ex.No:15(Part-B)
Date:
Calculator
AIM:
To create an applet for simple calculator to perform addition, subtraction, multiplications and division using button , label and text field classes
ALGORITHM:
STEP 1: Create a class calc which extends Applet super class
STEP 2: Define init() method to instantiate button,textcomponent
STEP 3: Call add() method to add components to applet container
STEP 4: Call addActionListener() method to listen the button action
STEP 5: Define actionPerformed() method to perform arithmetic operations when action event is triggered
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code = "calc.class" height="300" width="300"></applet>*/
public class calc extends Applet implements ActionListener
{
boolean flag=true;
String str2="";
double r=0.0,pre=0.0,t=0.0;
char lastaction=' ';
Button n[] = new Button[10];
Button b1,b2,b3,b4,b5;
TextArea t1;
public void init()
{
Font f1 = new Font("Serif", Font.BOLD, 12);
setFont(f1);
setForeground(Color.red);
setLayout(new GridLayout(5,5));
t1= new TextArea("",1,1,3);
// t1= new TextField( );
add(t1);
for(int i = 0; i < 10; i++)
{
n[i]=new Button(""+i);
add(n[i]);
n[i].addActionListener(this);
}
b1 = new Button("+");
b2 = new Button("-");
b3 = new Button("*");
b4 = new Button("/");
b5 = new Button("=");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str1=e.getActionCommand();
if(str1.equals("0"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("1"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("2"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("3"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("4"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("5"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("6"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("7"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("8"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("9"))
{
t1.append(str1);
str2 =t1.getText();
}
if(str1.equals("+"))
{
if(lastaction=='=')
pre=t;
else
{
r =Double.parseDouble(str2);
if (flag==true)
{
pre=0.0;
t=0.0;
}
t=r+pre;
pre=t;
}
lastaction='+';
flag=false;
t1.setText(" ");
}
if(str1.equals("-"))
{
if(lastaction=='=')
pre=t;
else
{
r =Double.parseDouble(str2);
System.out.println(str2);
if(flag==true)
{
pre=0.0;
t=0.0;
}
else
{
r=pre;
pre=Double.parseDouble(str2);
}
t=r-pre;
pre=t;
}
flag=false;
lastaction='-';
t1.setText(" ");
}
if(str1.equals("*"))
{
if(lastaction=='=')
pre=t;
else
{
r =Double.parseDouble(str2);
if(flag==true)
pre=1;
t=r*pre;
pre=t;
}
lastaction='*';
flag=false;
t1.setText(" ");
}
if(str1.equals("/"))
{
if(lastaction=='=')
pre=t;
else
{
r =Double.parseDouble(str2);
if(flag==true)
pre=1;
else
{
r=pre;
pre =Double.parseDouble(str2);
}
t=r/pre;
pre=t;
}
lastaction='/';
flag=false;
t1.setText(" ");
}
if(str1.equals("="))
{
switch(lastaction)
{
case '+' : t=t + Double.parseDouble(str2);
break;
case '-' : t=t - Double.parseDouble(str2);
break;
case '*' : t=t * Double.parseDouble(str2);
break;
case '/' : t=t / Double.parseDouble(str2);
break;
}
t1.setText(" ");
t1.setText(Double.toString(t));
lastaction='=';
}
}
}
OUTPUT
RESULT:
Thus the program Implementation of calcualtor has been executed and verified successfully.
Ex.No:16(Part-B)
Date:
Implementation of Scrollbar Component
AIM:
To create an applet for implementing three horizontal scrollbars to select value of colors simple calculator to perform addition, subtraction, multiplications and division using button , label and text field classes
ALGORITHM:
STEP 1: Create a class scrollbar which extends Applet super class implements
adjustmentlistener
STEP 2: Define init() method to instantiate scrollbar and label component, set grid layout
STEP 3: Call add() method to add components to applet container
STEP 4: Call addAdjustmentListener() method to listen the scrollbar action
STEP 5: Define adjustmentValuChanged() method to get integer value of scroll bar and set
these values to Color class
STEP 5: Define paint() method to set color and call fillRect() method to draw rectangle
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code = "scrollbar.class" height="300" width="300"></applet>*/
public class scrollbar extends Applet implements AdjustmentListener
{
int x,y,z;
Color c1;
Scrollbar s1,s2,s3;
Label l1,l2,l3;
public void init()
{
setLayout(new GridLayout(5,5,10,10));
l1 = new Label("Red");
l2 = new Label("Green");
l3 = new Label("Blue");
s1=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
s2=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
s3=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
add(l1);
add(s1);
add(l2);
add(s2);
add(l3);
add(s3);
s1.addAdjustmentListener(this);
s2.addAdjustmentListener(this);
s3.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
x = s1.getValue();
y = s2.getValue();
z = s3.getValue();
c1=new Color(x,y,z);
repaint();
}
public void paint(Graphics g)
{
g.setColor(c1);
g.fillRect(20,180,250,75);
}
}
OUTPUT
RESULT:
Thus the program Implementation of scrollbar has been executed and verified successfully.
Ex.No:17(Part-B)
Date:
Implementation of Thread
AIM:
To write a program for generating two threads , one for printing even numbers and other for printing odd numbers
ALGORITHM:
STEP 1: Create a class even which extends Thread super class
STEP 2: Define run() method to print even numbers
STEP 3: Create another class odd which extends Thread super class
STEP 4: Define run() method to print odd numbers
STEP 5: In the main class, create object for even and odd class and call start() method to start even and odd threads
PROGRAM:
class even extends Thread
{
public void run()
{
for(int i=0;i<=10;i+=2)
System.out.println("Even Number :"+i);
}
}
class odd extends Thread
{
public void run()
{
for(int i=1;i<=10;i+=2)
System.out.println("Odd Number:"+i);
}
}
class thread
{
public static void main(String args[])
{
even ob1 = new even();
odd ob2 = new odd();
ob1.start();
ob2.start();
}
}
OUTPUT
RESULT:
Thus the program Implementation of thread has been executed and verified successfully.
Ex.No:18(Part-A)
Date:
Implementation of User Define Exception
AIM:
To write a program to create our own exception sub class that throws if the sum of two integers is greater than 99
ALGORITHM:
STEP 1: Create a subclass Greaterthan99Exception which extends Exception super class
STEP 2: Greaterthan99Exception constructor calls the super class Exception constructor and
passes the problem “Your Sum is greater than 99” with super().
STEP 3: In the main class, read two numbers no1,no2 and calculate sum = no1+no2
STEP 3: If sum > 99 then create object for Greaterthan99Exception and pass “Your Sum is
greater than 99” to Greaterthan99Exception constructor . otherwise print sum.
PROGRAM:
import java.io.*;
class Greaterthan99Exception extends Exception
{
public Greaterthan99Exception(String exce)
{
super(exce);
//System.out.println(exce);
}
}
public class sum_of_two_integers
{
public static void main( String args[ ] ) throws Greaterthan99Exception
{
int no1,no2,sum=0;
DataInputStream din = new DataInputStream(System.in);
try
{
System.out.print("Enter First Number:");
no1 = Integer.parseInt(din.readLine());
System.out.print("Enter Second Number:");
no2 = Integer.parseInt(din.readLine());
sum=no1+no2;
if (sum>99)
{
Greaterthan99Exception e = new Greaterthan99Exception("Your Sum Exceeds 99");
throw e;
}
else
{
System.out.print("Sum:"+sum);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT
RESULT:
Thus the program Implementation of user define exception has been executed and verified successfully.
Ex.No:19(Part-A)
Date:
Creation of Text File using Byte Stream Classes
AIM:
To write a program to create a text file using byte stream classes
ALGORITHM:
STEP 1: Create a object din for data input stream class for getting input from console
STEP 2: Create a object os for file output stream class
STEP 3: Create data output stream object and pass os as argument to data output stream
STEP 4: Read a string from the console
STEP 5: Call writeBytes() method to write sequence of bytes to output stream
STEP 6: Repeat steps 4,5 until end of character „end‟ is encountered
PROGRAM:
import java.io.*;
class bytestream
{
public static void main(String args[])
{
String str;
try
{
DataInputStream din = new DataInputStream(System.in);
FileOutputStream os = new FileOutputStream("test.txt");
DataOutputStream dos = new DataOutputStream(os);
System.out.println("Enter Text");
for(;;)
{
str = din.readLine();
if(!(str.equals("end")))
dos.writeBytes(str);
else break;
}
os.close();
}
catch(IOException e)
{
System.out.print("Exception");
}
}
}
OUTPUT
RESULT:
Thus the program Creation of Text File using Byte Stream Classes has been executed and verified successfully.
Ex.No:20(Part-A)
Date:
File Copy
AIM:
To write a program to copy a file to another file
ALGORITHM:
STEP 1: Create character stream object‟ in‟ for file reader
STEP 2: Create character stream object „os‟ for file writer
STEP 3: Read a character from input file and check whether it is a end of file marker or not
STEP 4: if end of file is not reached then write that character to a output file and repeat step 3 .
Otherwise close the input file and output file object
PROGRAM:
import java.io.*;
class copyfile
{
public static void main(String args[])
{
int c;
try
{
FileReader in = new FileReader("test.txt");
FileWriter os = new FileWriter("test1.txt");
while((c=in.read())!=-1)
os.write(c);
os.close();
in.close();
}
catch(IOException e)
{
System.out.print("Exception");
}
}
}
OUTPUT
RESULT:
Thus the program File Copy has been executed and verified successfully.

No comments:

Post a Comment