shanmugasundari.files.wordpress.com · Web viewExp. No. 1. Develop a Java application to generate...
Transcript of shanmugasundari.files.wordpress.com · Web viewExp. No. 1. Develop a Java application to generate...
CS8383 OBJECT ORIENTED PROGRAMMING LAB
Exp. No. 1. Develop a Java application to generate Electricity bill. Create a class with the following members: Consumer no., consumer name, previous month reading, current month reading, type of EB connection (i.e domestic or commercial). Compute the bill amount using the following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
· First 100 units - Rs. 1 per unit
· 101-200 units - Rs. 2.50 per unit
· 201 -500 units - Rs. 4 per unit
· 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
· First 100 units - Rs. 2 per unit
· 101-200 units - Rs. 4.50 per unit
· 201 -500 units - Rs. 6 per unit
· 501 units - Rs. 7 per unit
PROGRAM
import java.util.*;
class ElectricityBill
{
int cno;
String cname;
int pr;
int cr;
String atype;
int reading;
double bamount;
public ElectricityBill(int no, String name,int prev, int cur,String acc)
{
this.cno=no;
this.cname=name;
this.pr=prev;
this.cr=cur;
this.atype=acc;
}
public void calculate()
{
reading=cr-pr;
if(atype.compareToIgnoreCase("domestic")==0)
{
if(reading<=100)
bamount=reading*1.0;
if(reading>100 && reading<=200)
bamount=100+((reading-100)*2.50);
if(reading>200 && reading<=500)
bamount=100+250 + (reading-200)*4;
if(reading>500)
bamount=100+250+ 1200+(reading-500)*6;
}
else if(atype.compareToIgnoreCase("commercial")==0)
{
if(reading<=100)
bamount=reading*2.0;
if(reading>100 && reading<=200)
bamount=200+((reading-100)*4.50);
if(reading>200 && reading<=500)
bamount=200+450 + (reading-200)*6;
if(reading>500)
bamount=200+450 +1800+(reading-500)*7;
}
else
{
System.out.println("Invalid Customer Type");
System.exit(0);
}
}
public void displaybill()
{
System.out.println("\t\t Electricity Bill \n");
System.out.println("\t\t________________\n");
System.out.println("customer Name :"+cname);
System.out.println("Customer Number :"+cno);
System.out.println("Customer Type :"+atype);
System.out.println("Total Reading :"+reading);
System.out.println("Total Amount : Rs."+bamount);
}
}
public class EBBill
{
public static void main(String ss[])
{int no=0;
String name=" ";
int prev=0;
int cur=0;
String type=" ";
try
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the Customer No\t");
no=s.nextInt();
System.out.println("Enter the Customer Name\t");
name=s.next();
System.out.println("Previous Month Reading\t");
prev=s.nextInt();
System.out.println("Current Month Reading\t");
cur=s.nextInt();
System.out.println("Account Type\t");
type=s.next();
}
catch(Exception ee)
{
System.out.println("Read Error");
}
ElectricityBill eb=new ElectricityBill(no,name,prev,cur,type);
eb.calculate();
eb.displaybill();
}
}
OUTPUT
G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
sivakumar
Previous Month Reading
200
Current Month Reading
280
Account Type
domestic
Electricity Bill
________________
customer Name :sivakumar
Customer Number :1
Customer Type :domestic
Total Reading :80
Total Amount : Rs.80.0
G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
siva
Previous Month Reading
200
Current Month Reading
450
Account Type
domestic
Electricity Bill
________________
customer Name :siva
Customer Number :1
Customer Type :domestic
Total Reading :250
Total Amount : Rs.550.0
G:\R17OOPSLAB\progs>
G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
siva
Previous Month Reading
200
Current Month Reading
450
Account Type
commercial
Electricity Bill
________________
customer Name :siva
Customer Number :1
Customer Type :commercial
Total Reading :250
Total Amount : Rs.950.0
G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
siva
Previous Month Reading
200
Current Month Reading
312
Account Type
jfdlj
Invalid Customer Tpe
G:\R17OOPSLAB\progs>
Exp. No. 2. Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa) , time converter (hours to minutes, seconds and vice versa) using packages.
PROGRAM
package myconverter;
import java.text.*;
class INRtoDOLLAR
{
double value;
public INRtoDOLLAR(double inr)
{
value=inr;
}
public double convert()
{
return value/68.25;
}
}
class DOLLARtoINR
{
double value;
public DOLLARtoINR(double inr)
{
value=inr;
}
public double convert()
{
return value*68.25;
}
}
class INRtoEURO
{
double value;
public INRtoEURO(double inr)
{
value=inr;
}
public double convert()
{
return value/80.1;
}
}
class EUROtoINR
{
double value;
public EUROtoINR(double inr)
{
value=inr;
}
public double convert()
{
return value*80.10;
}
}
class INRtoYEN
{
double value;
public INRtoYEN(double inr)
{
value=inr;
}
public double convert()
{
return value/1.92;
}
}
class YENtoINR
{
double value;
public YENtoINR(double inr)
{
value=inr;
}
public double convert()
{
return value*1.92;
}
}
class MILEtoKM
{
double value;
public MILEtoKM(double inr)
{
value=inr;
}
public double convert()
{
return value*1.60;
}
}
class KMtoMILE
{
double value;
public KMtoMILE(double inr)
{
value=inr;
}
public double convert()
{
return value/1.60;
}
}
class HOURStoMINUTES
{
double value;
public HOURStoMINUTES(double inr)
{
value=inr;
}
public double convert()
{
return value*60.0;
}
}
class MINUTEStoHOURS
{
double value;
public MINUTEStoHOURS(double inr)
{
value=inr;
}
public double convert()
{
return value/60.0;
}
}
class HOURStoSECONDS
{
double value;
public HOURStoSECONDS(double inr)
{
value=inr;
}
public double convert()
{
return value*3600.0;
}
}
class SECONDStoHOURS
{
double value;
public SECONDStoHOURS(double inr)
{
value=inr;
}
public double convert()
{
return value/3600.0;
}
}
import myconverter.*;
class Convert
{
public static void main(String str[])
{
int r=500,d=54,y=350,e=250,h=2,m=324,s=1200,mile=7,km=270;
INRtoDOLLAR obj1=new INRtoDOLLAR(r);
System.out.println("The Rs. "+r+" = USD "+obj1.convert());
DOLLARtoINR obj2= new DOLLARtoINR(d);
System.out.println("The USD "+d+" = Rs."+obj2.convert());
INRtoEURO obj3=new INRtoEURO(r);
System.out.println("The Rs. "+r+" = EURO "+obj3.convert());
EUROtoINR obj4= new EUROtoINR(e);
System.out.println("The EURO "+e+" = Rs."+obj4.convert());
INRtoYEN obj5=new INRtoYEN(r);
System.out.println("The Rs. "+r+" = YEN "+obj5.convert());
YENtoINR obj6= new YENtoINR(y);
System.out.println("The YEN "+y+" = Rs."+obj6.convert());
MILEtoKM obj7=new MILEtoKM(mile);
System.out.println("The "+mile+"Mile = "+obj7.convert()+" KM");
KMtoMILE obj8=new KMtoMILE(km);
System.out.println("The "+km+" KM = "+obj8.convert()+" Mile");
HOURStoMINUTES obj9=new HOURStoMINUTES(h);
System.out.println(h+" Hours = "+obj9.convert()+" Minutes");
MINUTEStoHOURS obj10=new MINUTEStoHOURS(m);
System.out.println(m+" Minutes = "+obj10.convert()+" Hours");
HOURStoSECONDS obj11=new HOURStoSECONDS(h);
System.out.println(h+" Hours = "+obj11.convert()+" Seconcds");
SECONDStoHOURS obj12=new SECONDStoHOURS(s);
System.out.println(s+" Seconds = "+obj10.convert()+" Hours");
}
}
OUTPUT
G:\R17OOPSLAB\progs>javac Convert.java
G:\R17OOPSLAB\progs>java Convert
The Rs. 500 = USD 7.326007326007326
The USD 54 = Rs.3685.5
The Rs. 500 = EURO 6.242197253433209
The EURO 250 = Rs.20025.0
The Rs. 500 = YEN 260.4166666666667
The YEN 350 = Rs.672.0
The 7Mile = 11.200000000000001 KM
The 270 KM = 168.75 Mile
2 Hours = 120.0 Minutes
324 Minutes = 5.4 Hours
2 Hours = 7200.0 Seconcds
1200 Seconds = 5.4 Hours
G:\R17OOPSLAB\progs>
Exp. No. 3. Develop a java application with Employee class with Emp_name, Emp_id, Address, Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund. Generate pay slips for the employees with their gross and net salary.
PROGRAM
import java.io.*;
import java.util.*;
class Employee
{
String ename;
int eid;
String eaddr;
String email;
String emobile;
public void getempdata()
{
Scanner sc= new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter Employee Name ");
ename=br.readLine();
System.out.println("Enter Employee Id ");
eid=sc.nextInt();
System.out.println("Enter Address of Employee ");
eaddr=br.readLine();
System.out.println("Enter E-Mail Id ");
email=br.readLine();
System.out.println("Enter Mobile Nummber ");
emobile=br.readLine();
}
catch(IOException ie)
{
System.out.println(ie);
}
}
}
class Programmer extends Employee
{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;
public Programmer(int pay)
{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}
public void displaybill()
{
System.out.println("Employee Name : "+ename);
System.out.println("Employee Id : "+eid);
System.out.println("Address of Employee :"+eaddr);
System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);
System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}
}
class AssistantProfessor extends Employee
{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;
public AssistantProfessor(int pay)
{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}
public void displaybill()
{
System.out.println("Employee Name : "+ename);
System.out.println("Employee Id : "+eid);
System.out.println("Address of Employee :"+eaddr);
System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);
System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}
}
class AssociateProfessor extends Employee
{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;
public AssociateProfessor(int pay)
{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}
public void displaybill()
{
System.out.println("Employee Name : "+ename);
System.out.println("Employee Id : "+eid);
System.out.println("Address of Employee :"+eaddr);
System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);
System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}
}
class Professor extends Employee
{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;
public Professor(int pay)
{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}
public void displaybill()
{
System.out.println("Employee Name : "+ename);
System.out.println("Employee Id : "+eid);
System.out.println("Address of Employee :"+eaddr);
System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);
System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}
}
class Inherit2
{
public static void main(String str[])
{
Programmer pr=new Programmer(6000);
AssistantProfessor ap=new AssistantProfessor(16500);
AssociateProfessor asp=new AssociateProfessor(34500);
Professor p= new Professor(36000);
System.out.println("Pay Bill for Programmer ");
pr.getempdata();
pr.calculate();
pr.displaybill();
System.out.println("Pay Bill for Assistant Professor ");
ap.getempdata();
ap.calculate();
ap.displaybill();
System.out.println("Pay Bill for Associate Professor ");
asp.getempdata();
asp.calculate();
asp.displaybill();
System.out.println("Pay Bill for Professor ");
p.getempdata();
p.calculate();
p.displaybill();
}
}
OUTPUT
G:\R17OOPSLAB\progs>java Inherit2
Pay Bill for Programmer
Enter Employee Name
SIVAKUMAR
Enter Employee Id
1
Enter Address of Employee
PERUNDURAI
Enter E-Mail Id
Enter Mobile Nummber
9994244540
Employee Name : SIVAKUMAR
Employee Id : 1
Address of Employee :PERUNDURAI
E-Mail Id [email protected]
Mobile Nummber 9994244540
Basic Pay : 6000
HRA : 600.0
DA : 5820.0
PF: 720.0
Staff Club : 60.0
Gross Pay : 12420.0
Net Pay : 11640.0
Pay Bill for Assistant Professor
Enter Employee Name
SENTHILKUMAR
Enter Employee Id
2
Enter Address of Employee
CHENNAI
Enter E-Mail Id
Enter Mobile Nummber
9994244541
Employee Name : SENTHILKUMAR
Employee Id : 2
Address of Employee :CHENNAI
E-Mail Id [email protected]
Mobile Nummber 9994244541
Basic Pay : 16500
HRA : 1650.0
DA : 16005.0
PF: 1980.0
Staff Club : 165.0
Gross Pay : 34155.0
Net Pay : 32010.0
Pay Bill for Associate Professor
Enter Employee Name
KANNAN
Enter Employee Id
3
Enter Address of Employee
ERODE
Enter E-Mail Id
Enter Mobile Nummber
9994244542
Employee Name : KANNAN
Employee Id : 3
Address of Employee :ERODE
E-Mail Id [email protected]
Mobile Nummber 9994244542
Basic Pay : 34500
HRA : 3450.0
DA : 33465.0
PF: 4140.0
Staff Club : 345.0
Gross Pay : 71415.0
Net Pay : 66930.0
Pay Bill for Professor
Enter Employee Name
MURALI
Enter Employee Id
4
Enter Address of Employee
SALEM
Enter E-Mail Id
Enter Mobile Nummber
9994244543
Employee Name : MURALI
Employee Id : 4
Address of Employee :SALEM
E-Mail Id [email protected]
Mobile Nummber 9994244543
Basic Pay : 36000
HRA : 3600.0
DA : 34920.0
PF: 4320.0
Staff Club : 360.0
Gross Pay : 74520.0
Net Pay : 69840.0
G:\R17OOPSLAB\progs>
Exp. No. 4. Design a Java interface for ADT Stack. Implement this interface using array. Provide necessary exception handling in both the implementations.
PROGRAM
interface StackI {
void push(int item) throws StackOverflow;
int pop() throws StackUnderflow;
boolean isEmpty();
}
class StackOverflow extends Exception
{
String msg=" ";
public StackOverflow(String title)
{
this.msg=title;
}
public String toString()
{
return "StackError:"+msg;
}
}
class StackUnderflow extends Exception
{
String msg=" ";
public StackUnderflow(String title)
{
this.msg=title;
}
public String toString()
{
return "StackError:"+msg;
}
}
class StackImpl implements StackI {
private int stck[];
private int tos;
StackImpl(int size)
{
stck = new int[size];
tos = -1;
}
public void push(int item) throws StackOverflow
{
if(tos==stck.length-1) // use length member
throw new StackOverflow("Stack Overflow");
else
{
stck[++tos] = item;
System.out.println("Item " + item+" Pushed");
}
}
public int pop() throws StackUnderflow
{
if(tos < 0)
throw new StackUnderflow("Stack underflow.");
else
return stck[tos--];
}
public boolean isEmpty()
{
if(tos<0)
return true;
else
return false;
}
}
class StackTest {
public static void main(String args[]) {
StackImpl mystack1 = new StackImpl(5);
StackImpl mystack2 = new StackImpl(8);
// push some numbers onto the stack
try
{
System.out.println("Capacity of Stack1 is 5 ");
for(int i=0; i<5; i++) mystack1.push(i);
System.out.println("Capacity of Stack2 is 8 ");
for(int i=0; i<9; i++) mystack2.push(i);
}
catch(StackOverflow sov)
{
System.out.println(sov);
}
// pop those numbers off the stack
try
{
System.out.println("Items in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Items in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
catch(StackUnderflow suf)
{
System.out.println(suf);
}
if(mystack1.isEmpty())
System.out.println("The stack1 is empty");
if(mystack2.isEmpty())
System.out.println("The stack2 is empty");
}
}
OUTPUT
G:\R17OOPSLAB\progs>java StackTest
Capacity of Stack1 is 5
Item 0 Pushed
Item 1 Pushed
Item 2 Pushed
Item 3 Pushed
Item 4 Pushed
Capacity of Stack2 is 8
Item 0 Pushed
Item 1 Pushed
Item 2 Pushed
Item 3 Pushed
Item 4 Pushed
Item 5 Pushed
Item 6 Pushed
Item 7 Pushed
StackError:Stack Overflow
Items in mystack1:
4
3
2
1
0
Items in mystack2:
7
6
5
4
3
2
1
0
StackError:Stack underflow.
The stack1 is empty
The stack2 is empty
G:\R17OOPSLAB\progs>
Exp. No. 5. Write a program to perform string operations using ArrayList. Write functions for the following
a. Append - add at end
b. Insert – add at particular index
c. Search
d. List all string starts with given letter
PROGRAM
import java.io.*;
import java.util.*;
class StringOp
{
public static void main(String args[]) throws IOException
{
int ch=0;
String str=null;
ArrayList al= new ArrayList();
do
{
System.out.println("String Operations using ArrayList");
System.out.println("1. Append - add at end ");
System.out.println("2. Insert at particular index");
System.out.println("3. Search");
System.out.println("4. List all string starts with given letter");
System.out.println("5. Exit");
System.out.println("Enter your Choice :");
Scanner sc= new Scanner(System.in);
ch=sc.nextInt();
switch(ch)
{
case 1:
try
{
System.out.println("Enter the String to be appended at end :");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
}
catch(IOException ie)
{
System.out.println(ie);
}
al.add(str);
System.out.println("Item Added at the end");
break;
case 2:
System.out.println("Enter the Position: ");
try
{
Scanner sc1= new Scanner(System.in);
int p=sc1.nextInt();
System.out.println("Enter the String to be inserted :");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
al.add(p,str);
System.out.println("Item inserted at the position "+p);
}
catch(IOException ie)
{
System.out.println(ie);
}
break;
case 3:
boolean res=false;
System.out.println("Enter the item to search ;");
try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
for(String obj:al)
{
if(obj.equals(str))
{
res=true;
break;
}
}
if(res)
System.out.println("Item found ");
else
System.out.println("Item Not found ");
}
catch(IOException ie)
{
System.out.println(ie);
}
break;
case 4:
System.out.println("The elements of array list are ");
System.out.println(al);
break;
}
}while (ch>0 && ch<5);
}
}
OUTPUT
G:\R17OOPSLAB\progs>javac StringOp.java
G:\R17OOPSLAB\progs>java StringOp
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
1
Enter the String to be appended at end :
siva
Item Added at the end
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
1
Enter the String to be appended at end :
senthil
Item Added at the end
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
1
Enter the String to be appended at end :
kannan
Item Added at the end
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
2
Enter the Position:
1
Enter the String to be inserted :
murugan
Item inserted at the position 1
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
4
The elements of array list are
[siva, murugan, senthil, kannan]
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
3
Enter the item to search ;
senthil
Item found
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
3
Enter the item to search ;
arun
Item Not found
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
5
G:\R17OOPSLAB\progs>
Exp. No.6. Write a Java Program to create an abstract class named Shape that contains two integers and an empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method print Area () that prints the area of the given shape.
PROGRAM
abstract class Shape
{
int no1,no2;
public abstract void printArea();
}
class Rectangle extends Shape
{
public Rectangle(int h,int w)
{
no1=h;
no2=w;
}
public void printArea()
{
System.out.println("Area of Rectangle is "+ (no1*no2));
}
}
class Circle extends Shape
{
public Circle(int r)
{
no1=r;
}
public void printArea()
{
System.out.println("Area of Circle is "+ (3.14*no1*no1));
}
}
class Triangle extends Shape
{
public Triangle(int b,int h)
{
no1=b;
no2=h;
}
public void printArea()
{
System.out.println("Area of Triangle is "+ (no1*no2)/2);
}
}
class Inherit1
{
public static void main(String str[])
{
Rectangle r= new Rectangle(3,4);
r.printArea();
Circle c= new Circle(5);
c.printArea();
Triangle t= new Triangle(3,4);
t.printArea();
}
}
OUTPUT
G:\R17OOPSLAB\progs>java Inherit1
Area of Rectangle is 12
Area of Circle is 78.5
Area of Triangle is 6
Exp. No. 7. Write a Java program to implement user defined exception handling.
PROGRAM
import java.io.*;
class MobileNumberException extends Exception
{
String str;
public MobileNumberException(String test)
{
str=test;
}
public String toString()
{
return "MobileNumberException : The Mobile Number has only "+str.length()+" digits / Contains Characters";
}
}
class MobileExp
{
public static void main(String str[])
{
String num=null;
try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Mobile Number ");
num=br.readLine();
}
catch(IOException ie)
{
System.out.println("IO Error " +ie);
}
try
{
if(num.length()==10 && num.matches("[0-9]+"))
System.out.println("Correct Mobile Number");
else
throw new MobileNumberException(num);
}
catch(MobileNumberException me)
{
System.out.println(me);
}
}
}
OUTPUT
G:\R17OOPSLAB\progs>javac MobileExp.java
G:\R17OOPSLAB\progs>java MobileExp
Enter the Mobile Number
9994244540
Correct Mobile Number
G:\R17OOPSLAB\progs>java MobileExp
Enter the Mobile Number
9382
MobileNumberException : The Mobile Number has only 4 digits / Contains Characters
G:\R17OOPSLAB\progs>java MobileExp
Enter the Mobile Number
abdef
MobileNumberException : The Mobile Number has only 5 digits / Contains Characters
G:\R17OOPSLAB\progs>
Exp. No. 8. Write a Java program that reads a file name from the user, displays information about whether the file exists, whether the file is readable, or writable, the type of file and the length of the file in bytes.
PROGRAM
import java.io.*;
import java.util.*;
class FileDetails
{
public static void main(String str[])
{
String fname=null;
try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File Name ");
fname=br.readLine();
}
catch(IOException ie)
{
System.out.println("IO Error " +ie);
}
File f= new File(fname);
if(f.exists())
System.out.println("File Exists");
else
System.out.println("File Not Available");
if(f.canWrite())
System.out.println("File has Write Permission");
if(f.canRead())
System.out.println("File has Read Permission");
if(f.canExecute())
System.out.println("File has Execute Permission");
System.out.println("File size is :"+f.length());
System.out.println("Last Modified Date :"+new Date(f.lastModified()));
}
}
OUTPUT
G:\R17OOPSLAB\progs>javac FileDetails.java
G:\R17OOPSLAB\progs>java FileDetails
Enter File Name
EBBill.java
File Exists
File has Write Permission
File has Read Permission
File has Execute Permission
File size is :2046
Last Modified Date :Mon Jun 18 19:45:59 IST 2018
G:\R17OOPSLAB\progs>
Exp. No. 9. Write a java program that implements a multi-threaded application that has three threads. First thread generates a random integer every 1 second and if the value is even, second thread computes the square of the number and prints. If the value is odd, the third thread will print the value of cube of the number.
PROGRAM
import java.util.*;
class SquareThread extends Thread
{
public int n;
public SquareThread(int no)
{
this.n = no;
System.out.println("Square Thread Started");
start();
}
public void run()
{
System.out.println("The Square of the Random Number " + n + " is "+(n*n));
}
}
class CubeThread extends Thread
{
public int n;
public CubeThread(int no)
{
this.n = no;
System.out.println("Cube Thread Started");
start();
}
public void run()
{
System.out.println("The Cube of the Random Number " + n + " is "+(n*n*n));
}
}
class RandThread extends Thread
{
public RandThread()
{
start();
}
public void run()
{
int v = 0;
Random r = new Random();
try
{
for (int i = 1; i<=10; i++)
{
v = r.nextInt(100);
System.out.println("Generated Random Number is " + v);
if (v % 2 == 0)
new SquareThread(v);
else
new CubeThread(v);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Randon Number Thread Interrupted");
}
}
}
public class MultiThreadDemo
{
public static void main(String[] args)
{
RandThread r = new RandThread();
}
}
OUTPUT
G:\R17OOPSLAB\progs>java MultiThreadDemo
Generated Random Number is 25
Cube Thread Started
The Cube of the Random Number 25 is 15625
Generated Random Number is 96
Square Thread Started
The Square of the Random Number 96 is 9216
Generated Random Number is 84
Square Thread Started
The Square of the Random Number 84 is 7056
Generated Random Number is 45
Cube Thread Started
The Cube of the Random Number 45 is 91125
Generated Random Number is 92
Square Thread Started
The Square of the Random Number 92 is 8464
Generated Random Number is 40
Square Thread Started
The Square of the Random Number 40 is 1600
Generated Random Number is 90
Square Thread Started
The Square of the Random Number 90 is 8100
Generated Random Number is 56
Square Thread Started
The Square of the Random Number 56 is 3136
Generated Random Number is 30
Square Thread Started
The Square of the Random Number 30 is 900
Generated Random Number is 86
Square Thread Started
The Square of the Random Number 86 is 7396
G:\R17OOPSLAB\progs>
Exp. No. 10. Write a java program to find the maximum value from the given type of elements using a generic function.
PROGRAM
import java.util.*;
class Generic1{
public static < E > void findMax(E[] elements)
{
Arrays.sort(elements);
System.out.println("The Maximum Element is " + elements[elements.length-1]);
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
Double[] doubleArray={1.5,2.5,3.9,22.5,9.0};
findMax( intArray );
findMax( charArray );
findMax(doubleArray);
}
}
OUTPUT
G:\R17OOPSLAB\progs>javac Generic1.java
G:\R17OOPSLAB\progs>java Generic1
The Maximum Element is 50
The Maximum Element is V
The Maximum Element is 22.5
G:\R17OOPSLAB\progs>
Exp. No. 11. Design a calculator using event-driven programming paradigm of Java with the following options.
a) Decimal manipulations
b) Scientific manipulations
PROGRAM
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements ActionListener {
JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;
ScientificCalculator() {
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent keyevent) {
char c = keyevent.getKeyChar();
if (c >= '0' && c <= '9') {
} else {
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = new JPanel();
buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));
boolean t = true;
b1 = new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);
b4 = new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5 = new JButton("5");
buttonpanel.add(b5);
b5.addActionListener(this);
b6 = new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);
b7 = new JButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8 = new JButton("8");
buttonpanel.add(b8);
b8.addActionListener(this);
b9 = new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);
zero = new JButton("0");
buttonpanel.add(zero);
zero.addActionListener(this);
plus = new JButton("+");
buttonpanel.add(plus);
plus.addActionListener(this);
min = new JButton("-");
buttonpanel.add(min);
min.addActionListener(this);
mul = new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
div = new JButton("/");
div.addActionListener(this);
buttonpanel.add(div);
addSub = new JButton("+/-");
buttonpanel.add(addSub);
addSub.addActionListener(this);
dot = new JButton(".");
buttonpanel.add(dot);
dot.addActionListener(this);
eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
rec = new JButton("1/x");
buttonpanel.add(rec);
rec.addActionListener(this);
sqrt = new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log = new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);
sin = new JButton("SIN");
buttonpanel.add(sin);
sin.addActionListener(this);
cos = new JButton("COS");
buttonpanel.add(cos);
cos.addActionListener(this);
tan = new JButton("TAN");
buttonpanel.add(tan);
tan.addActionListener(this);
pow2 = new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
pow3 = new JButton("x^3");
buttonpanel.add(pow3);
pow3.addActionListener(this);
exp = new JButton("Exp");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);
clr = new JButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center", buttonpanel);
cont.add("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("1")) {
if (z == 0) {
tfield.setText(tfield.getText() + "1");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "1");
z = 0;
}
}
if (s.equals("2")) {
if (z == 0) {
tfield.setText(tfield.getText() + "2");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "2");
z = 0;
}
}
if (s.equals("3")) {
if (z == 0) {
tfield.setText(tfield.getText() + "3");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "3");
z = 0;
}
}
if (s.equals("4")) {
if (z == 0) {
tfield.setText(tfield.getText() + "4");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "4");
z = 0;
}
}
if (s.equals("5")) {
if (z == 0) {
tfield.setText(tfield.getText() + "5");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "5");
z = 0;
}
}
if (s.equals("6")) {
if (z == 0) {
tfield.setText(tfield.getText() + "6");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "6");
z = 0;
}
}
if (s.equals("7")) {
if (z == 0) {
tfield.setText(tfield.getText() + "7");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "7");
z = 0;
}
}
if (s.equals("8")) {
if (z == 0) {
tfield.setText(tfield.getText() + "8");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "8");
z = 0;
}
}
if (s.equals("9")) {
if (z == 0) {
tfield.setText(tfield.getText() + "9");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "9");
z = 0;
}
}
if (s.equals("0")) {
if (z == 0) {
tfield.setText(tfield.getText() + "0");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "0");
z = 0;
}
}
if (s.equals("AC")) {
tfield.setText("");
x = 0;
y = 0;
z = 0;
}
if (s.equals("log")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("1/x")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = 1 /
Double.parseDouble(tfield.getText());
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("Exp")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^2")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.pow(Double.parseDouble(tfield.getText()), 2);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^3")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.pow(Double.parseDouble(tfield.getText()), 3);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("+/-")) {
if (x == 0) {
tfield.setText("-" + tfield.getText());
x = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals(".")) {
if (y == 0) {
tfield.setText(tfield.getText() + ".");
y = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals("+")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '+';
} else {
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '+';
y = 0;
x = 0;
}
tfield.requestFocus();
}
if (s.equals("-")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '-';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '/';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '/';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("*")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '*';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '*';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("MC")) {
m1 = 0;
tfield.setText("");
}
if (s.equals("MR")) {
tfield.setText("");
tfield.setText(tfield.getText() + m1);
}
if (s.equals("M+")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("SIN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.sin(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("COS")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("TAN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.tan(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("=")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
temp1 =
Double.parseDouble(tfield.getText());
switch (ch) {
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
tfield.setText("");
tfield.setText(tfield.getText() + result);
z = 1;
}
}
if (s.equals("n!")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
tfield.requestFocus();
}
double fact(double x) {
int er = 0;
if (x < 0) {
er = 20;
return 0;
}
double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}
public static void main(String args[]) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}
OUTPUT
Content Beyond the Syllabus (JDBC)
Develop a simple OPAC system for library using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database.
Program
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Library implements ActionListener
{
JRadioButton rbauthor = new JRadioButton("Search by Author Name");
JRadioButton rbbook = new JRadioButton("Search by Book Name");
JTextField textfld = new JTextField(30);
JLabel label = new JLabel("Enter Search Key");
JButton searchbutton = new JButton("Search");
JFrame frame = new JFrame();
JTable table;
DefaultTableModel model;
String query = "select * from library";
public Library()
{
frame.setTitle("Online Public Access Catalog(OPAC)");
frame.setSize(500,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(label);
p1.add(textfld);
ButtonGroup bg = new ButtonGroup();
bg.add(rbauthor);
bg.add(rbbook);
p2.setLayout(new FlowLayout());
p2.add(rbauthor);
p2.add(rbbook);
p2.add(searchbutton);
searchbutton.addActionListener(this);
p3.setLayout(new BorderLayout());
p3.add(p1,BorderLayout.NORTH);
p3.add(p2,BorderLayout.CENTER);
frame.add(p3,BorderLayout.NORTH);
addTable(query);
frame.setVisible(true);
}
public void addTable(String s)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn =
DriverManager.getConnection("jdbc:odbc:Library","","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(s);
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
model = new DefaultTableModel(1,cols);
table = new JTable(model);
String[] tabledata = new String[cols];
int i=0;
while(i
{
tabledata[i] = md.getColumnName(i+1);
i++;
}
model.addRow(tabledata);
while(rs.next())
{
for(i=0;i
tabledata[i] = rs.getObject(i+1).toString();
model.addRow(tabledata);
}
frame.add(table,BorderLayout.CENTER);
conn.close();
}catch(Exception e){}
}
public void actionPerformed(ActionEvent evt)
{
if(rbauthor.isSelected())
query = "select * from library where AuthorName like
'"+textfld.getText()+"%'";
if(rbbook.isSelected())
query = "select * from library where BookName like
'"+textfld.getText()+"%'";
while(model.getRowCount()>0)
model.removeRow(0);
frame.remove(table);
addTable(query);
}
public static void main(String[] args)
{
new Library();
}
}
OUTPUT
34