Você está na página 1de 97

2630006 Programming Skills IV (Java)

1. Observe the interactions involved in the process of booking a railway ticket.


Identify the various objects involved and the interactions between the objects in
order to solve a problem of booking a railway ticket.

import java.io.*;
class Ticket
public static void main(String S[]) throws IOException
{

BufferedReader
br
=
new
BufferedReader(new
InputStreamReader(System.in));
Train T[] = new Train[5];
T[0] = new Train("RAJDHANI
",100,200,300);
T[1] = new Train("SHATABDI
",130,200,120);
T[2] = new Train("KARNAVATI
",150,200,250);
T[3] = new Train("INTERCITY
",120,160,200);
T[4] = new Train("METRO EXPRESS ",100,100,100);
int x;
do
{
System.out.print("\n-------------------------------");
System.out.print("\n Main Menu ");
System.out.print("\n-------------------------------");
for(int i=0;i<5;i++)
{
System.out.print("\n"+(i+1) +" "+T[i].Train_Name + "
"+ T[i].TotalSeat());
}
System.out.print("\n0 EXIT ");
System.out.print("\n-------------------------------");
System.out.print("\n ENTER TRAIN NO : ");
x = Integer.parseInt(br.readLine());
if(x <= 5 && x > 0)
{
T[x-1].menu();
}
}
while(x!=0);
}
}
class Train
{
public
BufferedReader
br
=
new
BufferedReader(new
InputStreamReader(System.in));
public String Train_Name;
privateint c1,c2,c3;
public Train()
{
c1 = 0;
c2 = 0;
c3 = 0;
}
public Train(String Tnm,int First,int Second,int Third)
{
Train_Name = Tnm;
c1 = First;
c2 = Second;
c3 = Third;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)


}
public void class1()
{
c1--;
}
public void class2()
{
c2--;
}
public void class3()
{
c3--;
}
public int TotalSeat()
{
return (c1+c2+c3);
}
public void AvailableSeats()
{
System.out.print("\n-------------------------------");
System.out.print("\nTOTAL SEAT OF " + Train_Name );
System.out.print("\n-------------------------------");
System.out.print("\n FIRST CLASS :" + c1);
System.out.print("\n SECOND CLASS :" + c2);
System.out.print("\n GENERAL CLASS :" + c3);
System.out.print("\n-------------------------------");
System.out.print("\n TOTAL SEATS :" + TotalSeat());
System.out.print("\n-------------------------------");
}
public void GetSeatno() throws IOException
{
System.out.print("\n-------------------------------");
System.out.print("\n1 FOR FIRST CLASS");
System.out.print("\n2 FOR SECOND CLASS");
System.out.print("\n3 FOR GENERAL CLASS");
System.out.print("\n-------------------------------");
System.out.print("\nENTER YOURE CHOICE : ");
int ch = Integer.parseInt(br.readLine());
System.out.print("\n-------------------------------");
switch(ch)
{
case 1:this.class1(); break;
case 2:this.class2(); break;
case 3:this.class3(); break;
default: System.out.print("\nINVALID CHOICE CODE"); break;
}
}
void menu() throws IOException
{
System.out.print("\n-------------------------------");
System.out.print("\n 1 AVAILABLE SEATS IN TRAIN");
System.out.print("\n 2 GETSEAT NO");
System.out.print("\n 3 EXIT");
System.out.print("\n-------------------------------");
System.out.print ("\n ENTER YOUR CHOICE : ");
int x = Integer.parseInt(br.readLine());
System.out.print ("\n-------------------------------");
switch (x)
{

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)

Break;
}

case 1:
case 2:
case 3:
default:

Available Seats();
break;
GetSeatno();
break;
break;
System.out.print("\nINVALID CHOICE CODE");

}
2.

Write a simple java application to print a pyramid with 5 lines. The first line has
one character, 2nd line has two characters and so on. The character to be used in
the pyramid is taken as a command line argument.
class Asspra2
{
public static void main(String s[])
{

if(s.length <= 0)
System.out.print("Pass Arguments Properly...!");
else
{
char c = s[1].charAt(0);
for(int i=0;i<=Integer.parseInt(s[0]);i++)
{
for(int j=0;j<i;j++)
{
System.out.print(c);
}
System.out.print("\n");
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)

3. Write a Java application which takes several command line arguments, which are
supposed to be names of students and prints output as given below:
(Suppose we enter 3 names then output should be as follows)..
Number of arguments = 3
1.: First Student Name is = Tom
2.: Second Student Name is = Dick
3.: Third Student Name is = Harry
class Asspra3
{
public static void main(String s[])
{
String a[];
a = new String[20];
a[1] = "First";
a[2] = "Second";
a[3] = "Third";
a[4] = "Forth";
a[5] = "Fifth";
a[6] = "Sixth";
a[7] = "Seventh";
a[8] = "Eighth";
a[9] = "Nineth";
a[10] = "Tenth";
System.out.println("Number of arguments = " +s.length);
for(int i=0;i<s.length;i++)
System.out.println( (i+1) + ":" +a[i+1]+" Student Name is :
" +s[i]);
}
}

4.Write a class, with main method, which declares floating point variables and
observe the output of dividing the floating point values by a 0, also observe the effect

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)


of assigning a high integer value (8 digits and above) to a float and casting it back to
int and printing.
class Asspra4
{
public static void main(String s[])
{
float x = 10.1010f;
System.out.println(x/0);
int y = 1234567890;
System.out.println(y);
y = (int) x;
System.out.println(y);
}
}

5.Write a class called Statistics, which has a static method called average, which
takes a one-dimensional array for double type, as parameter, and prints the average
for the values in the array. Now write a class with the main method, which creates a
two-dimensional array for the four weeks of a month, containing minimum
temperatures for the days of the week(an array of 4 by 7), and uses the average
method of the Statistics class to compute and print the average temperatues for the
four weeks.
import java.util.*;
class Statistics
{
public static double average(double temp[])
{
int i=0;
double sum=0;
for(double x:temp)
{
i++;
sum += x;
}
return sum/i;
}
}
class Asspro5
{
public static void main(String args[])
{
double[][] a = new double[4][7];
a[0][0] = 25.34;
a[0][1] = 30.33;
a[0][2] = 35.34;
a[0][3] = 40.23;
a[0][4] = 45.12;
a[0][5] = 34.35;
a[0][6] = 22.56;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)


System.out.printf("Average
%3.2f",Statistics.average(a[0]));
a[3][0] = 49.00;
a[3][1] = 45.56;
a[3][2] = 48.55;
a[3][3] = 33.33;
a[3][4] = 12.20;
a[3][5] = 24.25;
a[3][6] = 45.20;
System.out.printf("\nAverage
%3.2f",Statistics.average(a[3]));
}
}

of

of

1st

3rd

Week

Week

6. Define a class called Product, each product has a name, a product code and
manufacturer name. define variables, methods and constructors, for the Product class.
Write a class called TestProduct, with the main method to test the methods and
constructors of the Product class.
import java.util.*;
import java.io.*;
class Product
{
private int P_code;
private String P_name;
private String P_manufacture;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public Product()
{
P_code = 0;
P_name = "";
P_manufacture = "";
}
public Product(int code,String name,String manufacture)
{
P_code = code;
P_name = name;
P_manufacture = manufacture;
}
public void setpdetail() throws IOException
{
System.out.printf("\nEnter Product Code
:");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)


P_code = Integer.parseInt(br.readLine());
System.out.printf("\nEnter Product Name
:");
P_name = br.readLine();
System.out.printf ("\nEnter Product Manufacture Name :");
P_manufacture = br.readLine ();
}
Public void getpdetail ()
{
System.out.printf
("\n=======================================");
System.out.printf ("\nProduct Code
: %d ", P_code);
System.out.printf ("\nProduct Name
: %S ",P_name);
System.out.printf("\nProduct Manufacture Name : %S ",P_manufacture);
System.out.printf("\n=======================================");
}
}
class Asspro6
{
public static void main(String s[])throws IOException
{
Product p1 = new Product();
Product p2 = new Product(1,"monitor","LG");
Product p3 = new Product();
p3.setpdetail();
p1.getpdetail();
p2.getpdetail();
p3.getpdetail();
}
}

7. Define a class called CartesianPoint, which has two instance variables, x and y. Provide the
methods getX() and getY() to return the values of the x and y values respectively, a method called
move() which would take two integers as parameters and change the values of x and y
respectively, a method called display() which would display the current values of x and y. Now
overload the method move() to work with single parameter, which would set both x and y to
thesame values, . Provide constructors with two parameters and overload to work with one
parameter as well. Now define a class called TestCartesianPoint, with the main method to test the
various methods in the CartesianPoint class.

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)

class Cartesian_Point
{
int x;
int y;
public Cartesian_Point(int x,int y)
{
this.x = x;
this.y = y;
}
public Cartesian_Point(int x)
{
this(x,x);
}
public String toString()
{
return "("+x+","+y+")";
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
public void move(int x,int y)
{
this.x = x;
this.y = y;
}
public void move(int x)
{
move(x,x);
}
}
class Test_Cartesian_Point
{
public static void main(String args[])
{
Cartesian_Point s = new Cartesian_Point(0,0);
System.out.println(s);
s.move(10,20);
System.out.println(s);
s.move(50);
System.out.println(s);
System.out.println(s.getx());
System.out.println(s.gety());
Cartesian_Point t = new Cartesian_Point(5);
System.out.println(t);
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)

8. Define a class called Triangle, which has constructor with three parameters, which are of type
CartesianPoint, defined in the exercise 7. Provide methods to find the area and the perimeter of the
Triangle, a method display() to display the three CartesianPoints separated by ':' character, a
method move() to move the first CartesianPoint to the specified x, y location, the move should take
care of relatively moving the other points as well, a method called rotate, which takes two
arguments, one is the CartesianPoint and other is the angle in clockwise direction. Overload the
move method to work with CartesianPoint as a parameter. Now define a class called TestTriangle to
test the various methods defined in the Triangle class. Similarly also define a class called Rectangle
which has four CartesianPoint.
class Triangle
{
Cartesian_Point p1;
Cartesian_Point p2;
Cartesian_Point p3;
public Triangle(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public void display()
{
System.out.print("["+p1+":"+p2+":"+p3+"]\n");
}
public String toString()
{
return "["+p1+":"+p2+":"+p3+"]\n";
}
public double area()
{
double a = Math.pow((p1.getx() - p2.getx()),2)+Math.pow((p1.gety() p2.gety()),2);
double b = Math.pow((p2.getx() - p3.getx()),2)+Math.pow((p2.gety() p3.gety()),2);
double c = Math.pow((p3.getx() - p1.getx()),2)+Math.pow((p3.gety() - p1.gety()),2);
a = Math.sqrt(a);
b = Math.sqrt(b);
c = Math.sqrt(c);
double s =(a+b+c)/2;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar

2630006 Programming Skills IV (Java)


double x = Math.sqrt(s*(s-a)*(s-b)*(s-c));
return x;
}
public void rotate(Cartesian_Point T,double angle)
{
}
}
class Rectangle
{
Cartesian_Point
Cartesian_Point
Cartesian_Point
Cartesian_Point

p1;
p2;
p3;
p4;

public Rectangle(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3,Cartesian_Point


p4)
{
double

Math.pow((p1.getx()

p2.getx()),2)+Math.pow((p1.gety()

double

Math.pow((p2.getx()

p3.getx()),2)+Math.pow((p2.gety()

p2.gety()),2);
p3.gety()),2);
double c = Math.pow((p3.getx() - p4.getx()),2)+Math.pow((p3.gety() - p4.gety()),2);
double d = Math.pow((p4.getx() - p1.getx()),2)+Math.pow((p4.gety() p1.gety()),2);
//System.out.print("\nA="+a+"\nB="+b+"\nC="+c+"\nD="+d);
if(a == c || a == b || a == d )
{
if( a == c && b == d)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
//
System.out.print("ab,cd");
}
else if( a == d && b == d)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
//
System.out.print("ad,bc");
}
}
else
System.out.print("Not A Rectangle");
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3,Cartesian_Point
p4)
{
this.p1
this.p2
this.p3
this.p4

=
=
=
=

p1;
p2;
p3;
p4;

}
public void display()

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 10

2630006 Programming Skills IV (Java)


{
System.out.print("["+p1+":"+p2+":"+p3+":"+p4+"]\n");
}
public String toString()
{
return "["+p1+":"+p2+":"+p3+":"+p4+"]\n";
}
public double area()
{
double a = Math.pow((p1.getx() - p2.getx()),2)+Math.pow((p1.gety() p2.gety()),2);
double b = Math.pow((p2.getx() - p3.getx()),2)+Math.pow((p2.gety() p3.gety()),2);
double c = Math.pow((p3.getx() - p4.getx()),2)+Math.pow((p3.gety() - p4.gety()),2);
double d = Math.pow((p4.getx() - p1.getx()),2)+Math.pow((p4.gety() p1.gety()),2);
a = Math.sqrt(a);
b = Math.sqrt(b);
c = Math.sqrt(c);
d = Math.sqrt(d);
if( a == c && b == d)
{
return a*b;
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
//
System.out.print("ab,cd");
return a*c;
}
else if( a == d && b == d)
{
//
System.out.print("ad,bc");
return a*b;
}
else
return 0;
}
public void rotate(Cartesian_Point T,double angle)
{
}
}
class Test
{
public static void main(String args[])
{
Cartesian_Point a = new Cartesian_Point(0,0);
Cartesian_Point b = new Cartesian_Point(5,0);
Cartesian_Point c = new Cartesian_Point(5,5);
Cartesian_Point d = new Cartesian_Point(0,5);
/*Triangle T1 = new Triangle(a,b,c);
System.out.print(T1);
System.out.print("AreaofT1 = "+T1.area()+"\n");
Cartesian_Point x1 = new Cartesian_Point(10);
System.out.print(T1);
T1.display();*/
Rectangle R1 = new Rectangle(a,b,c,d);
System.out.print("Area of Rectangle "+ R1.area());
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 11

2630006 Programming Skills IV (Java)

9. Override the toString, equals and the hashCode methods of the classes Triangle and Rectangle
defined in exercises 7 and 8 above, in appropriate manner, and also redefine the display methods
to use the toString method.
class Triangle
{
Cartesian_Point p1;
Cartesian_Point p2;
Cartesian_Point p3;
public Triangle(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public void display()
{
System.out.print("["+p1+":"+p2+":"+p3+"]\n");
}
public String toString()
{
return "["+p1+":"+p2+":"+p3+"]\n";
}
public double area()
{
double a = Math.pow((p1.getx() - p2.getx()),2)+Math.pow((p1.gety() p2.gety()),2);
double b = Math.pow((p2.getx() - p3.getx()),2)+Math.pow((p2.gety() p3.gety()),2);
double c = Math.pow((p3.getx() - p1.getx()),2)+Math.pow((p3.gety() - p1.gety()),2);
a = Math.sqrt(a);
b = Math.sqrt(b);
c = Math.sqrt(c);
double s =(a+b+c)/2;
double x = Math.sqrt(s*(s-a)*(s-b)*(s-c));
return x;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 12

2630006 Programming Skills IV (Java)


}
public void rotate(Cartesian_Point T,double angle)
{
}
}
class Rectangle
{
Cartesian_Point
Cartesian_Point
Cartesian_Point
Cartesian_Point

p1;
p2;
p3;
p4;

public Rectangle(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3,Cartesian_Point


p4)
{
double

Math.pow((p1.getx()

p2.getx()),2)+Math.pow((p1.gety()

double

Math.pow((p2.getx()

p3.getx()),2)+Math.pow((p2.gety()

p2.gety()),2);
p3.gety()),2);
double c = Math.pow((p3.getx() - p4.getx()),2)+Math.pow((p3.gety() - p4.gety()),2);
double d = Math.pow((p4.getx() - p1.getx()),2)+Math.pow((p4.gety() p1.gety()),2);
//System.out.print("\nA="+a+"\nB="+b+"\nC="+c+"\nD="+d);
if(a == c || a == b || a == d )
{
if( a == c && b == d)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
//
System.out.print("ab,cd");
}
else if( a == d && b == d)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
//
System.out.print("ad,bc");
}
}
else
System.out.print("Not A Rectangle");
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3,Cartesian_Point
p4)
{
this.p1
this.p2
this.p3
this.p4

=
=
=
=

p1;
p2;
p3;
p4;

}
public void display()
{
System.out.print("["+p1+":"+p2+":"+p3+":"+p4+"]\n");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 13

2630006 Programming Skills IV (Java)


}
public String toString()
{
return "["+p1+":"+p2+":"+p3+":"+p4+"]\n";
}
public double area()
{
double a = Math.pow((p1.getx() - p2.getx()),2)+Math.pow((p1.gety() p2.gety()),2);
double b = Math.pow((p2.getx() - p3.getx()),2)+Math.pow((p2.gety() p3.gety()),2);
double c = Math.pow((p3.getx() - p4.getx()),2)+Math.pow((p3.gety() - p4.gety()),2);
double d = Math.pow((p4.getx() - p1.getx()),2)+Math.pow((p4.gety() p1.gety()),2);
a = Math.sqrt(a);
b = Math.sqrt(b);
c = Math.sqrt(c);
d = Math.sqrt(d);
if( a == c && b == d)
{
return a*b;
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
//
System.out.print("ab,cd");
return a*c;
}
else if( a == d && b == d)
{
//
System.out.print("ad,bc");
return a*b;
}
else
return 0;
}
public void rotate(Cartesian_Point T,double angle)
{
}
}
class Test
{
public static void main(String args[])
{
Cartesian_Point a = new Cartesian_Point(0,0);
Cartesian_Point b = new Cartesian_Point(5,0);
Cartesian_Point c = new Cartesian_Point(5,5);
Cartesian_Point d = new Cartesian_Point(0,5);
/*Triangle T1 = new Triangle(a,b,c);
System.out.print(T1);
System.out.print("AreaofT1 = "+T1.area()+"\n");
Cartesian_Point x1 = new Cartesian_Point(10);
System.out.print(T1);
T1.display();*/
Rectangle R1 = new Rectangle(a,b,c,d);
System.out.print("Area of Rectangle "+ R1.area());
}
}
10. Define an abstract class called Polygon. Provide a constructor which takes an array of
CartesianPoint as parameter. Also provide method called perimeter, which calculates and returns
the perimeter of the Polygon. Declare abstract method area for this class. Also define a method
called move, which takes two parameters x and y to specify the destination for the first point of the

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 14

2630006 Programming Skills IV (Java)


Polygon, and overload to make it work for CartesianPoint as a parameter. Now update the classes
Triangle and Rectangle in the exercise 8 above, to be a subclass of the Polygon class. Write
appropriate class with main method to test the polymorphism in the area method.
abstract class Polygon
{
public Cartesian_Point[] x;
int n;
public Polygon(Cartesian_Point[] x)
{
int i=0;
for(Cartesian_Point y : x)
{
i++;
}
//System.out.print(i);
n = i;
this.x = new Cartesian_Point[i];
for(int j=0;j<n;j++)
{
this.x[j] = x[j];
}
}
public int perimeter()
{
return n;
}
abstract public double area();
public String toString()
{
//return ""+x[0];
String s = "[";
for(int i=0;i<n;i++)
s = s.concat(""+x[i]);
s=s.concat("]");
return s;
}
}
class Triangle extends Polygon
{
public Triangle(Cartesian_Point p1[])
{
super(p1);
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3)
{
x[0] = p1;
x[1] = p2;
x[2] = p3;
}
public void display()
{
System.out.print("["+x[0]+":"+x[1]+":"+x[2]+"]\n");
}
public String toString()
{
return "["+x[0]+":"+x[1]+":"+x[2]+"]\n";
}
public double area()
{
double a = Math.pow((x[0].getx() - x[1].getx()),2)+Math.pow((x[0].gety()
x[1].gety()),2);
double b = Math.pow((x[1].getx() - x[2].getx()),2)+Math.pow((x[1].gety()
x[2].gety()),2);
double c = Math.pow((x[2].getx() - x[0].getx()),2)+Math.pow((x[2].gety()
x[0].gety()),2);
a = Math.sqrt(a);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 15

2630006 Programming Skills IV (Java)


b = Math.sqrt(b);
c = Math.sqrt(c);
double s =(a+b+c)/2;
double A = Math.sqrt(s*(s-a)*(s-b)*(s-c));
return A;
}
public void rotate(Cartesian_Point T,double angle)
{
}
}
class Rectangle extends Polygon
{
public Rectangle(Cartesian_Point p[])
{
super(p);
double a = Math.pow((p[0].getx() - p[1].getx()),2)+Math.pow((p[0].gety() p[1].gety()),2);
double b = Math.pow((p[1].getx() - p[2].getx()),2)+Math.pow((p[1].gety() p[2].gety()),2);
double c = Math.pow((p[2].getx() - p[3].getx()),2)+Math.pow((p[2].gety() p[3].gety()),2);
double d = Math.pow((p[3].getx() - p[0].getx()),2)+Math.pow((p[3].gety() p[0].gety()),2);
//System.out.print("\nA="+a+"\nB="+b+"\nC="+c+"\nD="+d);
if(a == c || a == b || a == d )
{
if( a == c && b == d)
{
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
//
System.out.print("ab,cd");
}
else if( a == d && b == d)
{
//
System.out.print("ad,bc");
}
}
else
System.out.print("Not A Rectangle");
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3,Cartesian_Point
p4)
{
x[0] = p1;
x[1] = p2;
x[2] = p3;
x[3] = p4;
}
public void display()
{
System.out.print("["+x[0]+":"+x[1]+":"+x[2]+":"+x[3]+"]\n");
}
public String toString()
{
return "["+x[0]+":"+x[1]+":"+x[2]+":"+x[3]+"]\n";
}
public double area()
{
double a = Math.pow((x[0].getx() - x[1].getx()),2)+Math.pow((x[0].gety() x[1].gety()),2);
double b = Math.pow((x[1].getx() - x[2].getx()),2)+Math.pow((x[1].gety() x[2].gety()),2);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 16

2630006 Programming Skills IV (Java)


double

Math.pow((x[2].getx()

x[3].getx()),2)+Math.pow((x[2].gety()

double

Math.pow((x[3].getx()

x[0].getx()),2)+Math.pow((x[3].gety()

x[3].gety()),2);
x[0].gety()),2);
a = Math.sqrt(a);
b = Math.sqrt(b);
c = Math.sqrt(c);
d = Math.sqrt(d);
if( a == c && b == d)
{
return a*b;
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
//
System.out.print("ab,cd");
return a*c;
}
else if( a == d && b == d)
{
//
System.out.print("ad,bc");
return a*b;
}
else
return 0;
}
public void rotate(Cartesian_Point T,double angle)
{
}
}
class Test
{
public static void main(String args[])
{
Cartesian_Point a[] = new Cartesian_Point[5];
a[0] = new Cartesian_Point(0,0);
a[1] = new Cartesian_Point(5,0);
a[2] = new Cartesian_Point(5,5);
Polygon T1 = new Triangle(a);
System.out.print(T1);
System.out.print("AreaofT1 = "+T1.area()+"\n");
a[0] = new Cartesian_Point(0,0);
a[1] = new Cartesian_Point(5,0);
a[2] = new Cartesian_Point(5,5);
a[3] = new Cartesian_Point(0,5);
Rectangle R1 = new Rectangle(a);
System.out.print(R1);
System.out.print("AreaofR1 = "+R1.area()+"\n");
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 17

2630006 Programming Skills IV (Java)

11. Make the class CartesianPoint, belong to a package called edu.gtu.geometry, the classes
Polygon, Triangle and Rectangle belong to the package edu.gtu.geometry.shapes and the classes
TestCartesianPoint, TestTriangle, TestRectangle and TestPolygon belong to the package edu.gtu.test.
Use appropriate access specifiers for the classes and the members of the classes defined in the
earlier exercises. Now onwards all the classes must be defined in a package.
package mca.third.geometry;
public class Triangle extends Polygon
{
public Triangle(Cartesian_Point p1[])
{
super(p1);
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3)
{
x[0] = p1;
x[1] = p2;
x[2] = p3;
}
public void display()
{
System.out.print("["+x[0]+":"+x[1]+":"+x[2]+"]\n");
}
public String toString()
{
return "["+x[0]+":"+x[1]+":"+x[2]+"]\n";
}
public double area()
{
double a = Math.pow((x[0].getx() - x[1].getx()),2)+Math.pow((x[0].gety() x[1].gety()),2);
double b = Math.pow((x[1].getx() - x[2].getx()),2)+Math.pow((x[1].gety() x[2].gety()),2);
double c = Math.pow((x[2].getx() - x[0].getx()),2)+Math.pow((x[2].gety() x[0].gety()),2);
a = Math.sqrt(a);
b = Math.sqrt(b);
c = Math.sqrt(c);
double s =(a+b+c)/2;
double A = Math.sqrt(s*(s-a)*(s-b)*(s-c));
return A;
}
public void rotate(Cartesian_Point T,double angle)
{
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 18

2630006 Programming Skills IV (Java)


}
Test.java
import edu.gtu.geometry.*;
class Test
{
public static void main(String args[])
{
Cartesian_Point a[] = new Cartesian_Point[5];
a[0] = new Cartesian_Point(0,0);
a[1] = new Cartesian_Point(5,0);
a[2] = new Cartesian_Point(5,5);
Polygon T1 = new Triangle(a);
System.out.print(T1);
System.out.print("AreaofT1 = "+T1.area()+"\n");
a[0] = new Cartesian_Point(0,0);
a[1] = new Cartesian_Point(5,0);
a[2] = new Cartesian_Point(5,5);
a[3] = new Cartesian_Point(0,5);
Rectangle R1 = new Rectangle(a);
System.out.print(R1);
System.out.print("AreaofR1 = "+R1.area()+"\n");
}
}
Ractangle.java
package mca.third.geometry;
class Rectangle extends Polygon
{
public Rectangle(Cartesian_Point p[])
{
super(p);
double a = Math.pow((p[0].getx() - p[1].getx()),2)+Math.pow((p[0].gety() p[1].gety()),2);
double b = Math.pow((p[1].getx() - p[2].getx()),2)+Math.pow((p[1].gety() p[2].gety()),2);
double c = Math.pow((p[2].getx() - p[3].getx()),2)+Math.pow((p[2].gety() p[3].gety()),2);
double d = Math.pow((p[3].getx() - p[0].getx()),2)+Math.pow((p[3].gety() p[0].gety()),2);
//System.out.print("\nA="+a+"\nB="+b+"\nC="+c+"\nD="+d);
if(a == c || a == b || a == d )
{
if( a == c && b == d)
{
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
//
System.out.print("ab,cd");
}
else if( a == d && b == d)
{
//
System.out.print("ad,bc");
}
}
else
System.out.print("Not A Rectangle");
}
public void move(Cartesian_Point p1,Cartesian_Point p2,Cartesian_Point p3,Cartesian_Point
p4)

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 19

2630006 Programming Skills IV (Java)


{
x[0]
x[1]
x[2]
x[3]

=
=
=
=

p1;
p2;
p3;
p4;

}
public void display()
{
System.out.print("["+x[0]+":"+x[1]+":"+x[2]+":"+x[3]+"]\n");
}
public String toString()
{
return "["+x[0]+":"+x[1]+":"+x[2]+":"+x[3]+"]\n";
}
public double area()
{
double a = Math.pow((x[0].getx() - x[1].getx()),2)+Math.pow((x[0].gety()
x[1].gety()),2);
double b = Math.pow((x[1].getx() - x[2].getx()),2)+Math.pow((x[1].gety()
x[2].gety()),2);
double c = Math.pow((x[2].getx() - x[3].getx()),2)+Math.pow((x[2].gety()
x[3].gety()),2);
double d = Math.pow((x[3].getx() - x[0].getx()),2)+Math.pow((x[3].gety()
x[0].gety()),2);
a = Math.sqrt(a);
b = Math.sqrt(b);
c = Math.sqrt(c);
d = Math.sqrt(d);
if( a == c && b == d)
{
return a*b;
//
System.out.print("ac,bd");
}
else if( a == b && c == d)
{
//
System.out.print("ab,cd");
return a*c;
}
else if( a == d && b == d)
{
//
System.out.print("ad,bc");
return a*b;
}
else
return 0;
}
public void rotate(Cartesian_Point T,double angle)
{

}
}
Polygon.java
package mca.third.geometry;
abstract class Polygon
{
public Cartesian_Point[] x;
int n;
public Polygon(Cartesian_Point[] x)
{
int i=0;
for(Cartesian_Point y : x)
{
i++;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 20

2630006 Programming Skills IV (Java)


}
//System.out.print(i);
n = i;
this.x = new Cartesian_Point[i];
for(int j=0;j<n;j++)
{
this.x[j] = x[j];
}
}
public int perimeter()
{
return n;
}
abstract public double area();
public String toString()
{
//return ""+x[0];
String s = "[";
for(int i=0;i<n;i++)
s = s.concat(""+x[i]);
s=s.concat("]");
return s;
}
}
Cartesian_point.java
package mca.third.geometry;
public class Cartesian_Point
{
int x;
int y;
public Cartesian_Point(int x,int y)
{
this.x = x;
this.y = y;
}
public Cartesian_Point(int x)
{
this(x,x);
}
public String toString()
{
return "("+x+","+y+")";
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
public void move(int x,int y)
{
this.x = x;
this.y = y;
}
public void move(int x)
{
move(x,x);
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 21

2630006 Programming Skills IV (Java)


}

12. Update the classes Triangle and Rectangle, to throw an exception if the CartesianPoint
instances passed as parameter does not specify an appropriate Triangle or Rectangle. eg. In case of
Triangle, if the three points are in a straight line, or in case of Rectangle, if the lines when
connected cross each other.
import edu.gtu.geometry.*;
class Test
{
public static void main(String args[])throws DemoException
{
Cartesian_Point a[] = new Cartesian_Point[4];
a[0] = new Cartesian_Point(0,0);
a[1] = new Cartesian_Point(5,0);
a[2] = new Cartesian_Point(5,5);
Polygon T1 = new Triangle(a);
System.out.print(T1);
System.out.print("AreaofT1 = "+T1.area()+"\n");

//
//

a[0] = new Cartesian_Point(0,0);


a[1] = new Cartesian_Point(5,0);
a[2] = new Cartesian_Point(5,5);
a[3] = new Cartesian_Point(8,5);
a[4] = new Cartesian_Point(8,6);
Rectangle R1 = new Rectangle(a);
System.out.print(R1);
System.out.print("AreaofR1 = "+R1.area()+"\n");

}
}
DemoException.java
pacakge mca.third.geometry;
public class DemoException extends Exception
{
public DemoException(String msg)
{
super(msg);
}
public String toString()
{
return msg;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 22

2630006 Programming Skills IV (Java)


}
}

13. Define a class called PolygonManager, which manages a number of Polygon instances. Provide
methods to add, remove and list the Polygon instances managed by it.Test the methods of
PolygonManager by writing appropriate class with main method.
import java.io.*;
interface input
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
}
abstract class polygon_manager implements input
{
int x[];
int i;
int size;
int y[];
polygon_manager()
{
}
polygon_manager(int xy)
{
x=new int[xy];
y=new int[xy];
size=xy;
i=0;
}
abstract void display();
}
class triangle extends polygon_manager
{
triangle()
{
}
triangle(int xy)
{
super(xy);
}
void add()throws IOException
{
System.out.println("\nEnter the Three Co-Ordinates :");
for(i=0;i<3;i++)
{
System.out.println("Enter the x"+(i+1)+" And Y"+(i+1)+"=->");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 23

2630006 Programming Skills IV (Java)


x[i]=Integer.parseInt(br.readLine());
y[i]=Integer.parseInt(br.readLine());
}
}
void display()
{
System.out.print("\n\tTriangle :- {");
for(i=0;i<3;i++)
{
System.out.print("("+x[i]+","+y[i]+")");
}
System.out.print("}");
}
}
class rectangle extends polygon_manager
{
rectangle()
{
}
rectangle(int xy)
{
super(xy);
}
void add()throws IOException
{
System.out.println("\nEnter the four Co-Ordinates :");
for(i=0;i<4;i++)
{
System.out.println("Enter the x"+(i+1)+" And Y"+(i+1)+"=->");
x[i]=Integer.parseInt(br.readLine());
y[i]=Integer.parseInt(br.readLine());
}
}
void display()
{
System.out.print("\n\tRectangle :- {");
for(i=0;i<4;i++)
{
System.out.print("("+x[i]+","+y[i]+")");
}
System.out.print("}");
}
}
class pantagon extends polygon_manager
{
pantagon()
{
}
pantagon(int xy)
{
super(xy);
}
void add()throws IOException
{
System.out.println("\nEnter the five Co-Ordinates :");
for(i=0;i<5;i++)
{
System.out.println("Enter the x"+(i+1)+" And Y"+(i+1)+"=->");
x[i]=Integer.parseInt(br.readLine());
y[i]=Integer.parseInt(br.readLine());
}
}
void display()
{
System.out.print("\n\tPantagon :- {");
for(i=0;i<5;i++)

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 24

2630006 Programming Skills IV (Java)


{
System.out.print("("+x[i]+","+y[i]+")");
}
System.out.print("}");
}
}
class hexagon extends polygon_manager
{
hexagon()
{
}
hexagon(int xy)
{
super(xy);
}
void add()throws IOException
{
System.out.println("\nEnter the six Co-Ordinates :");
for(i=0;i<6;i++)
{
System.out.println("Enter the x"+(i+1)+" And Y"+(i+1)+"=->");
x[i]=Integer.parseInt(br.readLine());
y[i]=Integer.parseInt(br.readLine());
}
}
void display()
{
System.out.print("\n\tHexagon :- {");
for(i=0;i<6;i++)
{
System.out.print("("+x[i]+","+y[i]+")");
}
System.out.print("}");
}
}
class octagon extends polygon_manager
{
octagon()
{
}
octagon(int xy)
{
super(xy);
}
void add()throws IOException
{
System.out.println("\nEnter the Eight Co-Ordinates :");
for(i=0;i<8;i++)
{
System.out.println("Enter the x"+(i+1)+" And Y"+(i+1)+"=->");
x[i]=Integer.parseInt(br.readLine());
System.out.println();
y[i]=Integer.parseInt(br.readLine());
}
}
void display()
{
System.out.print("\n\tOctagon :- {");
for(i=0;i<8;i++)
{
System.out.print("("+x[i]+","+y[i]+")");
}
System.out.print("}");
}
}
class polygon implements input

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 25

2630006 Programming Skills IV (Java)


{
public static void main(String arg[])throws IOException
{
int ch,len=0,j=0,pos;
polygon_manager p[]=new polygon_manager[100];
while(true)
{
System.out.println("\nFunction Of Polygon...........");
System.out.println("1.Add");
System.out.println("2.Remove");
System.out.println("3.Display");
System.out.println("4.Exit");
System.out.println("Enter Your Choice =->");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
menuformat();
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
triangle t=new triangle(3);
t.add();
p[len]=t;
len++;
break;
case 2:
rectangle r=new rectangle(4);
r.add();
p[len]=r;
len++;
break;
case 3:
pantagon pa=new pantagon(5);
pa.add();
p[len]=pa;
len++;
break;
case 4:
hexagon h=new hexagon(6);
h.add();
p[len]=h;
len++;
break;
case 5:
octagon o=new octagon(8);
o.add();
p[len]=o;
len++;
break;
case 6:
break;
default :
System.out.println("\nPlz Enter 1 To 6 .................");
break;
}
break;
case 2 :
if(len<1)
{
System.out.println("\nPolygon does not exists............");
break;
}
System.out.println("\nList Of Polygon Is ..............");
for(j=0;j<len;j++)

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 26

2630006 Programming Skills IV (Java)


{
p[j].display();
}
menuformat();
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("\nEnter The Position =->");
pos=Integer.parseInt(br.readLine());
if(pos<len)
{
if(p[pos-1].size==3)
{
p[j]=null;
}
else
{
System.out.println("\nInvalid Selection................");
}
}
else
{
System.out.println("\nInvalid Position................");
}
break;
case 2:
System.out.println("\nEnter The Position =->");
pos=Integer.parseInt(br.readLine());
if(pos<len)
{
if(p[pos-1].size==4)
{
p[j]=null;
}
else
{
System.out.println("\nInvalid Selection................");
}
}
else
{
System.out.println("\nInvalid Position................");
}
break;
case 3:
System.out.println("\nEnter The Position =->");
pos=Integer.parseInt(br.readLine());
if(pos<len)
{
if(p[pos-1].size==5)
{
p[j]=null;
}
else
{
System.out.println("\nInvalid Selection................");
}
}
else
{
System.out.println("\nInvalid Position................");
}
break;
case 4:
System.out.println("\nEnter The Position =->");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 27

2630006 Programming Skills IV (Java)


pos=Integer.parseInt(br.readLine());
if(pos<len)
{
if(p[pos-1].size==6)
{
p[j]=null;
}
else
{
System.out.println("\nInvalid Selection................");
}
}
else
{
System.out.println("\nInvalid Position................");
}
break;
case 5:
System.out.println("\nEnter The Position =->");
pos=Integer.parseInt(br.readLine());
if(pos<len)
{
if(p[pos-1].size==8)
{
p[j]=null;
}
else
{
System.out.println("\nInvalid Selection................");
}
}
else
{
System.out.println("\nInvalid Position................");
}
break;
case 6:
break;
default :
System.out.println("\nPlz Enter 1 To 6 .................");
break;
}
break;
case 3 :
System.out.println("\nList Of Polygon Is ..............");
for(j=0;j<len;j++)
{
p[j].display();
}
break;
case 4 :
return ;
}
}
}
public static void menuformat()
{
System.out.println("\n\nSelect Any Polygon..................");
System.out.println("1.Tringle");
System.out.println("2.Rectangle");
System.out.println("3.Pantagon");
System.out.println("4.Hexagon");
System.out.println("5.Octagon");
System.out.println("6.Back To Main Menu...........");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 28

2630006 Programming Skills IV (Java)

System.out.println("Enter Your Choice =->");


}

14. Define a class called StatisticalData which manages a number of readings of type int. Provide a
method to setData available in the form of an array, a method add to individually add data of type
int, a method to reset the entire data, and methods to return the following statistics:
1. mean
2. median
3. mode
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class StatisticalData
{
int v[],N;
String vname;
public StatisticalData()
{
N=0;
vname="";
}
public void setData()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
System.out.printf("How many values You want to Enter? ");
try{
N=Integer.parseInt(br.readLine());
}
catch(IOException e)
{
System.out.println("Error while Reading from console");
}
v=new int[N];
System.out.printf("Enter variable Name and its values: ");
try{
vname = br.readLine();
for(i=0;i<N;i++)

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 29

2630006 Programming Skills IV (Java)


{
v[i]=Integer.parseInt(br.readLine());
}
}
catch(IOException e)
{
System.out.println("Error while Reading from console");
}
System.out.println("Variable Name: " + vname);
System.out.print("Your Data are: ");
for(i=0;i<N;i++)
{
System.out.print(" " + v[i]);
}
System.out.println();
}
public double Mean()
{
double m=0;
int i;
for(i=0;i<N;i++)
{
m=m+v[i];
}
m=m/N;
return m;
}
public double Median()
{
double m=0;
int temp[]=new int[N];
int i,j,x,n=N-1;
for(i=0;i<N;i++)
{
temp[i]=v[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(temp[j] > temp[j+1])
{
x=temp[j];
temp[j]=temp[j+1];
temp[j+1]=x;
}
}
}
if(N%2 == 0)
{
x=N/2;
m=temp[x];
x--;
m=m+temp[x];
m=m/2;
}
else
{
x=N/2;
System.out.println("IND: " + x);
m=temp[x];
}
return m;
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 30

2630006 Programming Skills IV (Java)

public double Mode()


{ double M,x,m;
M=Median();
x=Mean();
m=3*M-2*x;
return m;
}
public double Variance()
{
double var=0,m;
int i;
m=Mean();
for(i=0;i<N;i++)
{
var=var+(v[i]-m)*(v[i]-m);
}
var=var/(N-1);
return var;
}
public double StdDev()
{
double sd;
int i;
sd=Variance();
sd=Math.sqrt(sd);
return sd;
}
public double Percentile(int p)
{
if(p==0)
return 0.0;
double P,n;
int temp[]=new int[N];
int i,j,x;
for(i=0;i<N;i++)
{
temp[i]=v[i];
}
for(i=0;i<N-1;i++)
{
for(j=0;j<N-i-1;j++)
{
if(temp[j] > temp[j+1])
{
x=temp[j];
temp[j]=temp[j+1];
temp[j+1]=x;
}
}
}
if(p==100)
return temp[N-1];
else
{
P=p;
n=N;
n=P*n/100;
P=Math.ceil(n);
if(P-n > 0)
{
i=(int)P;
P=temp[i-1];

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 31

2630006 Programming Skills IV (Java)


}
else
{
i=(int)P;
P=temp[i]+temp[i-1];
P=P/2;
}
return P;
}
}
}
class P14
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StatisticalData s=new StatisticalData();
int ch=10,ch1=1,p=-1;
double result,Q3;
s.setData();
do
{
do
{
System.out.println("1. Set Data");
System.out.println("2. Mean");
System.out.println("3. Median");
System.out.println("4. Mode");
System.out.println("5. Variance");
System.out.println("6. Standard Deviation");
System.out.println("7. Percentile (between 0 - 100)");
System.out.println("8. Quartile (between 1 - 3)");
System.out.println("9. Interquartile Range");
System.out.println("10. Exit");
System.out.print("Enter Your Choice: ");
try{
ch=Integer.parseInt(br.readLine());
}
catch(IOException e)
{
System.out.println("Error while Reading from console");
}
}while(ch<1 || ch>10);
switch(ch)
{
case 1:
s.setData();
break;
case 2:
result=s.Mean();
System.out.println("Mean: " + result);
break;
case 3:
result=s.Median();
System.out.println("Median: " + result);
break;
case 4:
result=s.Mode();
System.out.println("Mode: " + result);
break;
case 5:
result=s.Variance();
System.out.println("Variance: " + result);
break;
case 6:
result=s.StdDev();

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 32

2630006 Programming Skills IV (Java)


System.out.println("Standard Deviation: " + result);
break;
case 7:
do
{
System.out.print("Which Percentile you want to calculate? ");
try{
p=Integer.parseInt(br.readLine());
}
catch(IOException e)
{
System.out.println("Error while Reading from console");
}
}while(p<0 || p>100);
result=s.Percentile(p);
System.out.println("Percentile: " + result);
break;
case 8:
do
{
System.out.println("1. First ");
System.out.println("2. Second ");
System.out.println("3. Third ");
System.out.print("Enter Your Choice: ");
try{
ch1=Integer.parseInt(br.readLine());
}
catch(IOException e)
{
System.out.println("Error while Reading from console");
}
}while(ch1<1 || ch1>3);
switch(ch1)
{
case 1:
result=s.Percentile(25);
System.out.println("First Quartile: " + result);
break;
case 2:
result=s.Percentile(50);
System.out.println("Second Quartile: " + result);
break;
case 3:
result=s.Percentile(75);
System.out.println("Third Quartile: " + result);
}
break;
case 9:
Q3=s.Percentile(75);
result=s.Percentile(25);
result=Q3-result;
System.out.println("Inter Quartile Range: " + result);
}
}while(ch != 10);
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 33

2630006 Programming Skills IV (Java)

15. Update the class StatisticalData, and define a method called loadFromCSV, which takes as
parameter an InputStream, where numeric data is available in an ASCII format, in a comma
separated form. Overload this method to take a File instance as parameter. Test the new methods
using appropriate data.
import java.util.*;
import java.io.*;
class StatisticalData
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int marks[];
int n;
StatisticalData(){
marks=new int[60];
n=0;
}
void add()throws IOException{
if(n==60) {
System.out.println("There is 60 student in the class...");
System.out.println("You can't enter any more marks.....");
}
else{
System.out.print("Enter Mark of Student : "+(n+1)+" : ");
try{
int temp=Integer.parseInt(br.readLine());
if(temp>100 || temp<0) {
System.out.println("Marks should be in range between 0 - 100...");
add();
}
else{
marks[n]=temp;
n++;
}
}
catch(NumberFormatException nfe) {
System.out.println("Marks can't be the String..... OR can not leave it
blank.....");
add();
}
}
}
float mean() {
display();
float sum=0;
for(int i=0;i<n;i++){

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 34

2630006 Programming Skills IV (Java)


sum+=marks[i];
}
return (sum/(n*1.0f));
}
float median(){
sort();
display();
float med=0;
int tmp=(n+1)/2;
if(n%2==0) {
med=(marks[tmp-1]+marks[tmp])/2.0f;
}
else {
med=marks[tmp-1];
}
return med;
}
void mode(){
display();
float m=0.0f;
int count[]=new int[n];
for(int i=0;i<n;i++){
count[i]=1;
for(int j=i+1;j<n;j++){
if(marks[i]==marks[j]) {
count[i]++;
}
}
}
int temp=1;
int temp1=-1;
for(int k=0;k<n;k++){
if(count[k]>temp) {
temp=count[k];
temp1=k;
}
}
System.out.println("Mode is/are .....");
if(temp1==-1) {
m=(3.0f*median())-(2.0f*mean());
System.out.println(m);
}
else{
for(int i=0;i<n;i++){
if(count[i]==temp) {
System.out.println(marks[i]);
}
}
}
}
float variance(){
float mean=mean();
float sum=0;
System.out.println("\n\n (X-Xbar) | (X-Xbar)^2 \n");
for(int i=0;i<n;i++){
System.out.println((marks[i]-mean)+" | "+((marks[i]-mean)*(marks[i]mean)));
sum+=(marks[i]-mean)*(marks[i]-mean);
}
return (sum/((n-1)*1.0f));
}
float standard_deviation(){
float variance = variance();
return ((float)(Math.sqrt(variance)));
}
int specified_percentile(int nth) {

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 35

2630006 Programming Skills IV (Java)


sort();
display();
int i=(int)Math.ceil(((nth*(n))/100.0f));
return (marks[i-1]);
}
float specified_quertile(int nth) {
sort();
display();
float sq=0.0f ;
float temp=((nth*(n+1))/4.0f);
int t=(int)(temp);
float k=temp%t;
if(k==0.0f) {
sq=marks[t-1];
}
else{
int i=(int)Math.ceil(temp);
sq=((marks[i-1]+marks[i-2])/2.0f);
}
return sq;
}
float interquarlite_rang(){
return (specified_quertile(3)-specified_quertile(1));
}
void load_from_csv(File f) throws IOException{
FileInputStream fis=new FileInputStream(f);
Vector v=new Vector();
v.add(fis);
loading_process(v,1);
}
void load_from_csv(InputStream istr) throws IOException{
Vector v1=new Vector();
v1.add(istr);
loading_process(v1,0);
}
void loading_process(Vector v,int ch1) throws IOException{
InputStream istr=null;
FileInputStream fis=null;
if(ch1==0){
istr=(InputStream)v.get(0);
}
else{
fis=(FileInputStream)v.get(0);
}
int asc=0,i=0;
int m[]=new int[60];
char[] str=new char[1];
String temp2="";
System.out.println("Your Data is as Bellow ....");
while(asc!=-1) {
if(ch1==0) {
asc=istr.read();
}
else{
asc=fis.read();
}
if(asc==44 || asc==13) {
int t=Integer.parseInt(temp2);
if(t>100 || t<0) {
System.out.println(t+" is not valid Mark...., is not Accepted");
}
else{
System.out.println(t+" is Accepted....");
m[i]=t;
i++;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 36

2630006 Programming Skills IV (Java)


}
temp2="";
}
else{
if(asc>=48 && asc<=57) {
str[0]=(char)asc;
String temp3=new String(str);
temp2=temp2.concat(temp3);
}
}
}
System.out.println("Your meaningfull data from CSV file found as follow....");
for (int j=0;j<i;j++){
System.out.println(m[j]);
}
int k=0;
while(k==0) {
System.out.print("\nSure you want to import this data ? (Y/N) :");
String ch=br.readLine();
if(ch.equalsIgnoreCase("Y") || ch.equalsIgnoreCase("N")){
if(ch.equalsIgnoreCase("Y")){
marks=new int[60];
n=i;
marks=m;
System.out.println("\n"+n+" Student's Mark imported....");
System.out.println("\nYour Data is Successfully imported....");
}
else if(ch.equalsIgnoreCase("N")){
System.out.println("\nYour previous data is as it is......\n Importation of data has been
cancelled....");
}
k=1;
}
else{
System.out.println("Enter Y (for Yes) \nEnter N (for No)... \nOtherwise System
can't recognize....");
}
}
}
void sort(){
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(marks[i]>marks[j]) {
int temp=marks[i];
marks[i]=marks[j];
marks[j]=temp;
}
}
}
}
void display(){
System.out.println("\n Your Data is .....\n");
for(int i=0;i<n;i++){
System.out.print(marks[i]+" ");
}
System.out.println("");
}
int get_size(){
return n;
}
}
class p15{
public static void main(String args[]) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StatisticalData s=new StatisticalData();
int ch=1;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 37

2630006 Programming Skills IV (Java)


while(ch!=0){
System.out.println("\nMain Menu");
System.out.println("01. Insert Mark");
System.out.println("02. Mean");
System.out.println("03. Median");
System.out.println("04. Mode");
System.out.println("05. Variance");
System.out.println("06. Standard Deviation");
System.out.println("07. Specified Percentile");
System.out.println("08. Specified Quarlite");
System.out.println("09. Interquartile Range");
System.out.println("10. Load Data from CSV file ( using Input Stream )");
System.out.println("11. Load Data from CSV file ( using File )");
System.out.println("0. Exit");
System.out.print("Enter your choice :");
try{
ch=Integer.parseInt(br.readLine());
}
catch(NumberFormatException nfx) {
System.out.println("You can not enter the string.... OR can not leave it blank.....");
ch=13;
}
if(s.get_size()==0 && ch!=1 && ch!=10 && ch!=11) {
if(ch>11) {
System.out.println("System can't recognize your choice,re-enter your
selection....");
}
else if( ch != 0 ) {
System.out.println("Enter the mark of student first.....");
}
}
else{
switch(ch) {
case 1:
String ch1="Y";
while(ch1.compareToIgnoreCase("N")!=0){
if(ch1.equalsIgnoreCase("Y") ||
ch1.equalsIgnoreCase("N")){
s.add();
}
else{
System.out.println("Enter Y (for Yes) \nEnter N (for
No)... Otherwise System can't recognize....");
}
System.out.print("Want to add more ? (Y/N) :");
ch1=br.readLine();
}
break;
case 2:
System.out.println("Mean : "+s.mean());
break;
case 3:
System.out.println("Median : "+s.median());
break;
case 4:
s.mode();
break;
case 5:
System.out.println("Variance : "+s.variance());
break;
case 6:
System.out.println("Standard Deviation :
"+s.standard_deviation());
break;
case 7:
int flag=0;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 38

2630006 Programming Skills IV (Java)


while(flag==0) {
try{
System.out.print("Enter value for Specified Percentile (0100) :");
int p=Integer.parseInt(br.readLine());
if( p > 100 || p < 1 ) {
System.out.println("Enter between 1 - 100 .....");
}
else{
System.out.println("Specified Percentile for intput " + p + "
is : "+s.specified_percentile(p));
flag=1;
}
}
catch(NumberFormatException e) {
System.out.println("Enter between 1 - 100 .....");
}
}
break;
case 8:
flag=0;
while(flag==0) {
try{
System.out.print("Enter Value for Specified Quarlite (13) :");
int q=Integer.parseInt(br.readLine());
if( q > 3 || q < 1) {
System.out.println("Enter between 1 - 3 ......");
}
else{
System.out.println("Specified Quarlite for input "
+ q + " is : "+s.specified_quertile(q));
flag=1;
}
}
catch(NumberFormatException e){
System.out.println("Enter between 1 - 3 ......");
}
}
break;
case 9:
System.out.print("Interquartile Range : "+
s.interquarlite_rang());
break;
case 10:
flag=0;
String path="";
while(flag==0) {
try{
System.out.print("Enter the Path for csv file :");
path=br.readLine();
String ext=path.substring(path.length()-4);
if(ext.equalsIgnoreCase(".csv")){
InputStream istr=new FileInputStream(path);
s.load_from_csv(istr);
istr.close();
flag=1;
}
else{
System.out.println("System can't recognize your input....");
System.out.println("System can support only .CSV file....");
}
}
catch(FileNotFoundException e) {
System.out.println("System can't find your inputed path....");
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 39

2630006 Programming Skills IV (Java)


catch(StringIndexOutOfBoundsException e){
System.out.println("Can't leave it blank...");
}
}
break;
case 11:
flag=0;
path="";
while(flag==0) {
String ext="";
try{
System.out.print("Enter the Path for csv file :");
path=br.readLine();
ext=path.substring(path.length()-4);
}
catch(StringIndexOutOfBoundsException e){
System.out.println("Cannot be Blank");
}
if(ext.equalsIgnoreCase(".csv")) {
try{
File f=new File(path);
s.load_from_csv(f);
flag=1;
}
catch(FileNotFoundException e) {
System.out.println("System can't find your inputed path....");
}
}
else{
System.out.println("System can't recognize your input....");
System.out.println("System can support only .CSV file....");
}
}
break;
case 12:
s.display();
break;
case 0:
break;
default:
System.out.println("System can't recognize your choice, reenter your selection....");
break;
}
}
}
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 40

2630006 Programming Skills IV (Java)

16. A college maintains the information about the marks of the students of a class in a text file with
fixed record length. Each line in the file contains data of one student. The first 25 characters have
the name of the student, next 12 characters have marks in the four subjects, each subject has 3
characters. Create a class called StudentMarks, which has studentName, and marks for four
subjects. Provide appropriate getter methods and constructors, for this class. Write an application
class to load the file into an array of StudentMarks. Use the StatisticalData class to compute the
statistics mean, median, mode for each of the subjects in the class.
import java.io.*;
import java.util.*;
class Student_Marks
{
int Rollno;
String stu_name;
int sub_marks[] = new int[5];
Student_Marks()
{}
Student_Marks(int Rollno,String stu_name,int mark1,int mark2,int mark3,int mark4,int
mark5)
{
this.Rollno = Rollno;
this.stu_name = stu_name;
sub_marks[0] = mark1;
sub_marks[1] = mark2;
sub_marks[2] = mark3;
sub_marks[3] = mark4;
sub_marks[4] = mark5;
}
public void getdata()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Rollno: ");
this.Rollno = Integer.parseInt(br.readLine());
System.out.print("Enter Name: ");
this.stu_name = br.readLine();

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 41

2630006 Programming Skills IV (Java)


for(int i=0;i<5;i++)
{
System.out.print("Enter Marks["+(i+1)+"] : ");
this.sub_marks[i] = Integer.parseInt(br.readLine());
}
}
public int getmark(int i)
{
return sub_marks[i];
}
public int getTotal()
{
int sum = 0;
for(int x : sub_marks)
sum += x;
return sum;
}
public String getName()
{
return stu_name;
}
public int getRollno()
{
return Rollno;
}
public String toString()
{
return Rollno+","+stu_name+","+sub_marks[0]+
","+sub_marks[1]+
","+sub_marks[2]+
","+sub_marks[3]+
","+sub_marks[4];
}
public void writedata()throws IOException
{
FileOutputStream fos = new FileOutputStream("F:\\Anand.txt",true);
PrintStream out = new PrintStream(fos);
out.printf("%3d,%-25S,%3d,%3d,%3d,%3d,
%3d",this.Rollno,this.stu_name,this.sub_marks[0],this.sub_marks[1],this.sub_marks[2],this.sub_mar
ks[3],this.sub_marks[4]);
out.println();
}
}
class Application
{
public static void main(String args[]) throws IOException
{
ArrayList<Student_Marks> s1 = new ArrayList();
Statistical_data sd = new Statistical_data();
Student_Marks temp = new Student_Marks(1,"Amit",40,40,40,40,40);
s1.add(temp);
temp = new Student_Marks(1,"Amit",40,40,40,40,40);
s1.add(temp);
temp = new Student_Marks(1,"Suresh",30,30,30,30,30);
s1.add(temp);
temp = new Student_Marks(1,"Mahesg",20,20,20,20,20);
s1.add(temp);
temp = new Student_Marks(1,"Paresh",60,70,60,60,60);
s1.add(temp);
for(int i=0;i<s1.size();i++)
{
System.out.println(s1.get(i));
s1.get(i).writedata();
}
float sub_mark[][]= new float[5][s1.size()];

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 42

2630006 Programming Skills IV (Java)


for(int i=0;i<s1.size();i++)
{
sub_mark[0][i] = s1.get(i).getmark(0);
sub_mark[1][i] = s1.get(i).getmark(1);
sub_mark[2][i] = s1.get(i).getmark(2);
sub_mark[3][i] = s1.get(i).getmark(3);
sub_mark[4][i] = s1.get(i).getmark(4);
}
sd.set(sub_mark[0]);
System.out.println("\nDetails of sub1");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
System.out.printf("\npercentile %3.2f",sd.percentile(20));
System.out.printf("\nquartile %3.2f",sd.quartile(2));
System.out.printf("\nIQR
%3.2f",sd.IQR());
sd.set(sub_mark[1]);
System.out.println("\nDetails of sub2");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
System.out.printf("\npercentile %3.2f",sd.percentile(20));
System.out.printf("\nquartile %3.2f",sd.quartile(2));
System.out.printf("\nIQR
%3.2f",sd.IQR());
sd.set(sub_mark[2]);
System.out.println("\nDetails of sub3");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
System.out.printf("\npercentile %3.2f",sd.percentile(20));
System.out.printf("\nquartile %3.2f",sd.quartile(2));
System.out.printf("\nIQR
%3.2f",sd.IQR());
sd.set(sub_mark[3]);
System.out.println("\nDetails of sub4");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
System.out.printf("\npercentile %3.2f",sd.percentile(20));
System.out.printf("\nquartile %3.2f",sd.quartile(2));
System.out.printf("\nIQR
%3.2f",sd.IQR());
sd.set(sub_mark[4]);
System.out.println("\nDetails of sub5");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 43

2630006 Programming Skills IV (Java)


System.out.printf("\npercentile %3.2f",sd.percentile(20));
System.out.printf("\nquartile %3.2f",sd.quartile(2));
System.out.printf("\nIQR
%3.2f",sd.IQR());
}
}

17. In the above exercise, use multithreading, to compute the statistics, after loading the
StudentMarks from the file, for marks information available for different classes available from files
placed in a directory. Create atleast five files in a directory with fixed record length to test your
code.
import java.io.*;
import java.util.*;
class Student_Marks
{
int Rollno;
String stu_name;
int sub_marks[] = new int[5];
Student_Marks()
{}
Student_Marks(int Rollno,String stu_name,int mark1,int mark2,int mark3,int mark4,int
mark5)
{
this.Rollno = Rollno;
this.stu_name = stu_name;
sub_marks[0] = mark1;
sub_marks[1] = mark2;
sub_marks[2] = mark3;
sub_marks[3] = mark4;
sub_marks[4] = mark5;
}
public void getdata()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Rollno: ");
this.Rollno = Integer.parseInt(br.readLine());
System.out.print("Enter Name: ");
this.stu_name = br.readLine();
for(int i=0;i<5;i++)
{
System.out.print("Enter Marks["+(i+1)+"] : ");
this.sub_marks[i] = Integer.parseInt(br.readLine());
}
}
public int getmark(int i)
{
return sub_marks[i];
}
public int getTotal()
{
int sum = 0;
for(int x : sub_marks)

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 44

2630006 Programming Skills IV (Java)


sum += x;
return sum;
}
public String getName()
{
return stu_name;
}
public int getRollno()
{
return Rollno;
}
public String toString()
{
return Rollno+","+stu_name+","+sub_marks[0]+
","+sub_marks[1]+
","+sub_marks[2]+
","+sub_marks[3]+
","+sub_marks[4];
}
public void writedata()throws IOException
{
FileOutputStream fos = new FileOutputStream("F:\\Anand.txt",true);
PrintStream out = new PrintStream(fos);
out.printf("%3d,%-25S,%3d,%3d,%3d,%3d,
%3d",this.Rollno,this.stu_name,this.sub_marks[0],this.sub_marks[1],this.sub_marks[2],this.sub_mar
ks[3],this.sub_marks[4]);
out.println();
}
}
class Application
{
public static void main(String args[]) throws IOException
{
ArrayList<Student_Marks> s1 = new ArrayList();
Statistical_data sd = new Statistical_data();
synchronized(sd){}
Student_Marks temp = new Student_Marks(1,"Anand",10,20,30,40,50);
s1.add(temp);
temp = new Student_Marks(1,"Amit",10,20,30,40,50);
s1.add(temp);
temp = new Student_Marks(1,"Suresh",10,20,30,40,50);
s1.add(temp);
temp = new Student_Marks(1,"Mahesg",10,20,30,40,50);
s1.add(temp);
temp = new Student_Marks(1,"Paresh",10,20,30,40,50);
s1.add(temp);
for(int i=0;i<s1.size();i++)
{
System.out.println(s1.get(i));
s1.get(i).writedata();
}
float sub_mark[][]= new float[5][s1.size()];
for(int i=0;i<s1.size();i++)
{
sub_mark[0][i] = s1.get(i).getmark(0);
sub_mark[1][i] = s1.get(i).getmark(1);
sub_mark[2][i] = s1.get(i).getmark(2);
sub_mark[3][i] = s1.get(i).getmark(3);
sub_mark[4][i] = s1.get(i).getmark(4);
}
System.out.println(1);
sd.set(sub_mark[0]);
sd.thread1.start();
sd.thread1.
System.out.println("\nDetails of sub1");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 45

2630006 Programming Skills IV (Java)

System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
sd.set(sub_mark[1]);
System.out.println("\nDetails of sub2");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
sd.set(sub_mark[2]);
System.out.println("\nDetails of sub3");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
sd.set(sub_mark[3]);
System.out.println("\nDetails of sub4");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
sd.set(sub_mark[4]);
System.out.println("\nDetails of sub5");
System.out.print("=========================================");
System.out.printf("\nMEAN
%3.2f",sd.mean());
System.out.printf("\nMEDIAN
%3.2f",sd.median());
System.out.printf("\nMODE
%3.2f",sd.mode());
System.out.printf("\nVARIANCE %3.2f",sd.variance());
System.out.printf("\nSD
%3.2f",sd.SD());
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 46

2630006 Programming Skills IV (Java)

18. Dasher is an information-efficient text-entry interface, driven by natural continous pointing


gestures. Dasher is a competitive text-entry system wherever a full-size keyboard cannot be used.
Dasher is a zooming interface. You point where you want to go, and the display zooms in wherever
you point. The world into which you are zooming is painted with letters, so that any point you zoom
in on corresponds to a piece of text. The more you zoom in, the longer the piece of text you have
written. You choose what you write by choosing where to zoom. To make the interface efficient, we
use the predictions of a language model to determine how much of the world is devoted to each
piece of text. Probable pieces of text are given more space, so they are quick and easy to select.
Improbable pieces of text (for example, text with spelling mistakes) are given less space, so they
are harder to write. The language model learns all the time: if you use a novel word once, it is
easier to write next time.
Write a class in Java which models the probabilities for the alphabets in a langauge as the
starting alphabet and then the probatilities for the subsequent alphabets which may follow the
alphabet and so on leading to the end of word. The probabilities may be built by reading a text file
containing lots of texts in the given language. (Hint: create a class to represent a node, which has
an alphabet and its probability and each node has capability of maintaining a list of subsequent
nodes). (Advanced question)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="prg5_26" height=1000 width=1000>
</applet>
*/
public class prg5_26 extends Applet implements ActionListener
{
Label lno,lnm,lgen,lage,ldept,ldesc,lbs,lda,lma,lit,lpf,lgs,lded,lnt;
TextField tno,tnm,tgen,tage,tbs,tda,tma,tit,tpf,tgs,tded,tnt;
Checkbox male,female;
CheckboxGroup cbg;
List lst;
Choice dept;
Button desp,reset;
TextArea ta;
String str;
public void init()
{
lno=new Label("Emp No:");
lnm=new Label("Emp Name:");
lgen=new Label("Gender:");
lage=new Label("Age:");
ldept=new Label("Department:");
ldesc=new Label("Desicnation:");
lbs=new Label("Basic Salary:");
lda=new Label("DA:");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 47

2630006 Programming Skills IV (Java)


lma=new Label("MA:");
lpf=new Label("PF:");
lit=new Label("IT:");
lgs=new Label("Gross Salary:");
lded=new Label("Deduction:");
lnt=new Label("Net Salary:");
tno=new TextField();
tnm=new TextField();
tage=new TextField();
tbs=new TextField();
tda=new TextField();
tma=new TextField();
tpf=new TextField();
tit=new TextField();
tgs=new TextField();
tded=new TextField();
tnt=new TextField();
tgs.setEditable(false);
tded.setEditable(false);
tnt.setEditable(false);
cbg=new CheckboxGroup();
male=new Checkbox("Male",cbg,true);
female=new Checkbox("Female",cbg,true);
dept=new Choice();
dept.add("Marketing");
dept.add("Production");
dept.add("Sales");
dept.add("QC");
dept.add("HR");
dept.add("Account");
lst=new List(3);
lst.add("Manager");
lst.add("Dept. Manager");
lst.add("Assi Manager");
lst.add("Executive");
lst.add("Jun Executive");
lst.add("pueon");
desp=new Button("Display");
reset=new Button("Reset");
desp.addActionListener(this);
reset.addActionListener(this);
ta=new TextArea();
setLayout(null);
lno.setBounds(10,10,80,20);
add(lno);
tno.setBounds(100,10,80,20);
add(tno);
lnm.setBounds(10,40,80,20);
add(lnm);
tnm.setBounds(100,40,80,20);
add(tnm);
lgen.setBounds(10,70,80,20);
add(lgen);
male.setBounds(100,70,80,20);
add(male);
female.setBounds(200,70,80,20);
add(female);
lage.setBounds(10,100,80,20);
add(lage);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 48

2630006 Programming Skills IV (Java)


tage.setBounds(100,100,80,20);
add(tage);
ldept.setBounds(10,130,80,20);
add(ldept);
dept.setBounds(100,130,80,20);
add(dept);
ldesc.setBounds(200,130,80,20);
add(ldesc);
lst.setBounds(300,130,200,60);
add(lst);
lbs.setBounds(10,170,80,20);
add(lbs);
tbs.setBounds(100,170,80,20);
add(tbs);
lda.setBounds(10,200,80,20);
add(lda);
tda.setBounds(100,200,80,20);
add(tda);
lit.setBounds(200,200,80,20);
add(lit);
tit.setBounds(300,200,80,20);
add(tit);
lma.setBounds(10,230,80,20);
add(lma);
tma.setBounds(100,230,80,20);
add(tma);
lpf.setBounds(200,230,80,20);
add(lpf);
tpf.setBounds(300,230,80,20);
add(tpf);
desp.setBounds(130,260,80,20);
add(desp);
reset.setBounds(230,260,80,20);
add(reset);
lgs.setBounds(10,290,80,20);
add(lgs);
tgs.setBounds(100,290,80,20);
add(tgs);
lded.setBounds(200,290,80,20);
add(lded);
tded.setBounds(300,290,80,20);
add(tded);
lnt.setBounds(100,320,80,20);
add(lnt);
tnt.setBounds(200,320,80,20);
add(tnt);
ta.setBounds(100,350,350,200);
add(ta);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==desp)
{
if(tno.getText().equals("")
||
tnm.getText().equals("")
tage.getText().equals("")
||
tbs.getText().equals("")
||
tda.getText().equals("")
tma.getText().equals("") || tit.getText().equals("") || tpf.getText().equals(""))
{
str="Please Enter all fields";
ta.setText(str);
}
else
{
int a,bs,da,ma,it,pf,gr,de,net,flag,b;
str="";

Enrolment No: 145253693056

||
||

Name: Pandya Meet Pankajkumar 49

2630006 Programming Skills IV (Java)

b=0;a=0;bs=0;da=0;ma=0;it=0;pf=0;gr=0;de=0;net=0;flag=0;
try
{
a=Integer.parseInt(tno.getText());
}
catch(Exception e)
{
str = str + "Invalid N0. \n";
flag = 1;
}
try
{
for(int i=0;i<tnm.getText().length();i++)
{
if( (tnm.getText().charAt(i)<97 ||
tnm.getText().charAt(i)>122 ) &&
(tnm.getText().charAt(i)<65 ||
tnm.getText().charAt(i)>90 ) &&
(tnm.getText().charAt(i)!=32 ) )
{
throw new Exception("");
}
}
}
catch(Exception e)
{
str = str + "Invalid NAME. \n";
flag = 1;
}
try
{
b=Integer.parseInt(tage.getText());
}
catch(Exception e)
{
str = str + "Invalid age. \n";
flag = 1;
}
try
{
da=Integer.parseInt(tda.getText());
}
catch(Exception e)
{
str = str + "Invalid DA. \n";
flag = 1;
}
try
{
ma=Integer.parseInt(tma.getText());
}
catch(Exception e)
{
str = str + "Invalid MA. \n";
flag = 1;
}
try
{
pf=Integer.parseInt(tpf.getText());
}
catch(Exception e)
{
str = str + "Invalid PF. \n";
flag = 1;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 50

2630006 Programming Skills IV (Java)


}
try
{
it=Integer.parseInt(tit.getText());
}
catch(Exception e)
{
str = str + "Invalid IT. \n";
flag = 1;
}
try
{
bs=Integer.parseInt(tbs.getText());
}
catch(Exception e)
{
str = str + "Invalid Basic. \n";
flag = 1;
}
if (flag==0)
{
gr=da+ma;
de=it+pf;
net=bs+gr-de;
tgs.setText(""+gr);
tded.setText(""+de);
tnt.setText(""+net);
str="Employ no" + tno.getText();
str=str+"\nEmp Nm:"+tnm.getText();
str=str+"\nEmp Nm:"+tnm.getText();
if(male.getState())
{
str=str+"\nGender:"+male.getLabel();
}
if(female.getState())
{
str=str+"\nGender:"+female.getLabel();
}
str=str+"\t age:"+tage.getText();
str=str+"\n Department:"+dept.getSelectedItem();
str=str+"\n desgnation:"+lst.getSelectedItem();
str=str+"\n Basic Salary:"+tbs.getText();
str=str+" Net Salary:"+tnt.getText();
}
ta.setText(str);
}
}
if(ae.getSource()==reset)
{
tno.setText("");
tnm.setText("");
tage.setText("");
dept.select(0);
lst.select(0);
tbs.setText("");
tda.setText("");
tma.setText("");
tit.setText("");
tpf.setText("");
tgs.setText("");
tded.setText("");
tnt.setText("");
ta.setText("");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 51

2630006 Programming Skills IV (Java)


}
}
}

19.Create an applet which has a TextField to accept a URL string, and displays the document of the
URL string in a new browser window.
import java.awt.*;
import java.net.*;
import java.applet.*;
import java.awt.event.*;

public class gtu_30 extends Applet implements ActionListener


{
TextField urlField;
Button goButton;
// This varable will determine if the URL should be loaded
// or if an error message should appear.
boolean UrlOnError;
// The URL that we want to display
URL userUrl;
public void init()
{
setLayout(new FlowLayout());
urlField = new TextField("Enter url ex:google.com");
goButton = new Button("Go!");
urlField.addActionListener(this);
goButton.addActionListener(this);
add(urlField);
add(goButton);
}
public void paint(Graphics g)
{
// Will display when correct URL are entered and when the applet starts.
// !UrlOnError means "do if UrlOnError is false";
if (!UrlOnError)
g.drawString("Type your URL and click go!",20,80);
// A help message to display when a bad URL has been typed.
// In this case an URL without a ".com" domain.

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 52

2630006 Programming Skills IV (Java)


else
{
g.drawString("Malformed URL: "+userUrl,20,80);
g.drawString("This Applet only allows .com domains",20,100);
}
}
public void actionPerformed(ActionEvent act)
{
// Start with good hope...
UrlOnError = false;
// Save the data of the textfield.
String temp = urlField.getText();
// If the URL is longer than 6 characters.
if (temp.length() > 6)
{
// Then check if it starts with "http://"
if (!temp.substring(0,7).toUpperCase().equals("HTTP://"))
// if not then append it to it.
temp = "Http://" + temp;
}
// if it's not longer than 6 chars then it will surely miss
// the "http://" part. So we'll fix that.
else temp = "Http://" + temp;
// Now that the Http:// is there we'll check if it's a .com URL
// If the index of ".com" is -1 that means it isn't there.
if (temp.indexOf(".com") == -1)
// So we'll show an error message later
UrlOnError = true;
// Now it's time to transform the String to a real URL
try
{
// This will do that.
userUrl = new URL(temp);
}
// You MUST try-catch this method.
// If it is still wrong then we'll show an error message too.
catch (Exception e)
{
UrlOnError = true;
}
// Show the user what you have done with his typed in URL
urlField.setText(userUrl.toString());
// And finally load a new browser window and show the page.
// If it was right of course.
if (!UrlOnError)
// This will do so. Note that the "_blank" part can be
// replaced with "_self" or "_parent" like in HTML.
// even frame targets are possible.
getAppletContext().showDocument(userUrl,"_blank");
// Now show the error message or nothing if it was right.
repaint();
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 53

2630006 Programming Skills IV (Java)

20.Consider two types of residency, a Flat or a Villa. All types of residences have an area (square
yards) and a rate (per square yard). The property price of a residency is by default calculated as
area * rate. In case of Flat, the price get incremented by the maintenance charges, and in case of
Villa the price is incremented by furniture charges. Now define the following classes in a
common package called residence.
1. An abstract class called Residency, with appropriate methods and constructors.
2. Two sub-classes called Flat and Villa, which inherit from the Residence class and override
the appropriate methods, from Residency class.
3. Also override appropriate methods from the Object class.
package residence;
abstract class Residency
{
float price,area,rate;
Residency()
{
area=0;
rate=0;
setprice();
}
public Residency(float a, float b)
{
area=a;
rate=b;
setprice();
}
public void setprice()
{
price=area*rate;
}
public void display()
{
System.out.println("Price="+price);
}
abstract void moveprice();
}
//flat.java
public class Flat extends Residency
{
int mainten;
Flat()
{
super();
}
public Flat(float a, float r)
{
super(a,r);
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 54

2630006 Programming Skills IV (Java)


public void setdata(int a)
{
mainten=a;
moveprice();
}
public void moveprice()
{
price+=mainten;
}
}
//villa.java
class Villa extends Residency
{
int furnit;
Villa()
{
super();
}
public Villa(float a, float r)
{
super(a,r);
}
public void setdata(int a)
{
furnit=a;
moveprice();
}
public void moveprice()
{
price+=furnit;
}
}
//Main file Tuto_7.java
import residence.*;
class Tuto_7
{
public static void main(String s[])
{
System.out.println("..........price........");
System.out.println("");
Flat objf=new Flat(1000.0f,250.5f);
objf.setdata(500);
objf.display();
// Villa objv=new Villa(2000.0f,650.5f);
// objv.setdata(700);
//objv.display();
}
}
OUTPUT::

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 55

2630006 Programming Skills IV (Java)

21. Consider the above exercise and define the following:


1. Appropriate class(es) implementing the Comparator interface to make comparison of Residence
based on the area, rate or price. These class(es) may be defined in the residence.util package.
2. A class called PropertyList as part of the residence package, which maintains various
Residence objects in an appropriate data structure. has methods to add residence, remove
residence, get residence list in price range, get residence list in area range.
//import Residence.Flat_Q20;
//import Residence.Villa_Q20;
import java.io.*;
class Q20
{
public static void main(String args[]) throws Exception
{
Flat_Q20 f1 = new Flat_Q20(200,20000,5000);
Flat_Q20 f2 = new Flat_Q20();
Villa_Q20 v1 = new Villa_Q20(300,30000,15000);
Villa_Q20 v2 = new Villa_Q20();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println(" MENU ");
System.out.println("\n 1. Flat");
System.out.println(" 2. Villa");
System.out.println(" 3. EXIT");
System.out.print("\n Enter your Choice :- ");
int ch = Integer.parseInt(br.readLine());
switch(ch)
{
case 1: f2.Get();
System.out.println("\n"+f1);
f2.Display();
if(f1.equals(f2))
{
System.out.println("Both are Equals..");
}
else
{
System.out.println("Both are Different..");
}
break;
case 2: v2.Get();
System.out.println("\n"+v1);
v2.Display();
if(v1.equals(v2))
{
System.out.println("Both are Equals..");
}
else
{

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 56

2630006 Programming Skills IV (Java)


System.out.println("Both are Different..");
}
break;
case 3: System.exit(0);
}
}
}
}
//package Residence;
//import java.io.*;
class Flat_Q20 extends Residency_Q20
{
private double Maint_Charges;
public Flat_Q20()
{
Maint_Charges = 20000;
}
public Flat_Q20(double area, double rate, double Maint_Charges)
{
super(area,rate);
this.Maint_Charges = Maint_Charges;
}
public double getMaint_Charges()
{
return Maint_Charges;
}
public void Get() throws Exception
{
super.Get();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n Enter the Maintenance Charges :- ");
Maint_Charges = Double.parseDouble(br.readLine());
}
public double Price()
{
double total = getArea() * getRate() + Maint_Charges;
return total;
}
public String toString()
{
return
"\nFlat(Area="+getArea()+",Rate="+getRate()
+",Maintanance="+Maint_Charges+",Price="+Price()+")";
}
public boolean equals(Object o)
{
Flat_Q20 f = (Flat_Q20)o;
return (this.getArea()==f.getArea()
this.Maint_Charges==f.Maint_Charges);
}
public int hasCode()
{
return 1;
}
public void Display()
{
System.out.println("_______________________________");
System.out.println("
Flat Information
");
System.out.println("_______________________________");
System.out.println("\n Area =
"+getArea());

Enrolment No: 145253693056

&&

this.getRate()==f.getRate()

&&

Name: Pandya Meet Pankajkumar 57

2630006 Programming Skills IV (Java)


System.out.println("\n Rate =
"+getRate());
System.out.println("\n Maintenance =
"+Maint_Charges);
System.out.println("\n Price =
"+Price());
System.out.println("_______________________________");
}
}
//package Residence;
//import java.io.*;
abstract class Residency_Q20
{
private double area;
private double rate;
public Residency_Q20()
{
area = 500;
rate = 3000;
}
public Residency_Q20(double area, double rate)
{
this.area = area;
this.rate = rate;
}
public double getArea()
{
return area;
}
public double getRate()
{
return rate;
}
public void Get() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n Enter the Area :- ");
area = Double.parseDouble(br.readLine());
System.out.print("\n Enter the Rate :- ");
rate = Double.parseDouble(br.readLine());
}
abstract public double Price();
abstract public void Display();
}
//package Residence;
//import java.io.*;
class Villa_Q20 extends Residency_Q20
{
private double Furniture_Charges;
public Villa_Q20()
{
Furniture_Charges = 20000;
}
public Villa_Q20(double area, double rate, double Furniture_Charges)
{
super(area,rate);
this.Furniture_Charges = Furniture_Charges;
}
public double getFurniture_Charges()
{
return Furniture_Charges;
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 58

2630006 Programming Skills IV (Java)


public void Get() throws Exception
{
super.Get();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n Enter Furniture Charges :- ");
Furniture_Charges = Double.parseDouble(br.readLine());
}
public double Price()
{
double total = getArea() * getRate() + Furniture_Charges;
return total;
}
public String toString()
{
return
"\nVilla(Area="+getArea()+",Rate="+getRate()
+",Furniture="+Furniture_Charges+",Price="+Price()+")";
}
public boolean equals(Object o)
{
Villa_Q20 v = (Villa_Q20)o;
return (this.getArea()==v.getArea() && this.getRate()==v.getRate() &&
this.Furniture_Charges==v.Furniture_Charges);
}
public int hasCode()
{
return 2;
}
public void Display()
{
System.out.println("_______________________________");
System.out.println("
Villa Information
");
System.out.println("_______________________________");
System.out.println("\n Area =
"+getArea());
System.out.println("\n Rate =
"+getRate());
System.out.println("\n Furniture =
"+Furniture_Charges);
System.out.println("\n Price =
"+Price());
System.out.println("_______________________________");
}
}
//import Residence.Residency_Q20;
//import Residence.Flat_Q20;
//import Residence.Villa_Q20;
//import java.io.*;
//import java.util.*;
class PropertyList_Q21
{
public static void main(String args[]) throws Exception
{
List <Residency_Q20> l = new ArrayList<Residency_Q20>();
ListIterator i = null;
Residency_Q20 r = null;
Flat_Q20 f = new Flat_Q20();
Villa_Q20 v = new Villa_Q20();
int ch1, ch2;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("__________________________");
System.out.println(" Property Management ");
System.out.println("__________________________");
System.out.println("1. Add Residence");
System.out.println("2. Remove Residence");
System.out.println("3. Get Residence List in Price Range");
System.out.println("4. Get Residence List in Area Range");
System.out.println("5. Display ALL");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 59

2630006 Programming Skills IV (Java)


System.out.println("6. EXIT");
System.out.print("\n Enter your Choice :- ");
ch1 = Integer.parseInt(br.readLine());
switch(ch1)
{
case 1: System.out.print("\n Enter 1 for Flat && 2 for Villa :- ");
ch2 = Integer.parseInt(br.readLine());
if(ch2 == 1)
{
f = new Flat_Q20();
f.Get();
r = f;
l.add(r);
}
else
{
v = new Villa_Q20();
v.Get();
r = v;
l.add(r);
}
break;
case 2: System.out.print("\n Enter 1 for Flat && 2 for Villa :- ");
ch2 = Integer.parseInt(br.readLine());
if(ch2 == 1)
{
r = f;
l.remove(r);
}
else
{
r = v;
l.remove(r);
}
break;
case 3:
System.out.print("\nEnter Minimum Price : ");
double min = Double.parseDouble(br.readLine());
System.out.print("\nEnter Maximum Price : ");
double max = Double.parseDouble(br.readLine());
i = l.listIterator();
while(i.hasNext())
{
r=(Residency_Q20)i.next();
if(r.Price()>=min && r.Price()<=max)
r.Display();
else
System.out.println("No Any Residence Available...");
}
break;
case 4: System.out.print("\nEnter Minimum Area Range : ");
min = Double.parseDouble(br.readLine());
System.out.print("\nEnter Maximum Area Range : ");
max = Double.parseDouble(br.readLine());
i = l.listIterator();
while(i.hasNext())
{
r=(Residency_Q20)i.next();
if(r.getArea()>=min && r.getArea()<=max)
r.Display();
else
System.out.println("No Any Residence Available...");
}
break;
case 5:

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 60

2630006 Programming Skills IV (Java)


i = l.listIterator();
while(i.hasNext())
{
r = (Residency_Q20)i.next();
r.Display();
}
break;
case 6: System.exit(0);
}
}
}
}
//package Residence.util;
//import java.util.*;
//import Residence.Flat_Q20;
class FlatAreaComparator_Q21 implements Comparator
{
public int compare(Object o1, Object o2)
{
Flat_Q20 f1 = (Flat_Q20)o1;
Flat_Q20 f2 = (Flat_Q20)o2;
if(f1.getArea() > f2.getArea())
return 1;
else if(f1.getArea() < f2.getArea())
return -1;
else
return 0;
}
}
//package Residence.util;
//import java.util.*;
//import Residence.Flat_Q20;
class FlatPriceComparator_Q21 implements Comparator
{
public int compare(Object o1, Object o2)
{
Flat_Q20 f1 = (Flat_Q20)o1;
Flat_Q20 f2 = (Flat_Q20)o2;
if(f1.Price() > f2.Price())
return 1;
else if(f1.Price() < f2.Price())
return -1;
else
return 0;
}
}
//package Residence.util;
//import java.util.*;
//import Residence.Flat_Q20;
class FlatRateComparator_Q21 implements Comparator
{
public int compare(Object o1, Object o2)
{
Flat_Q20 f1 = (Flat_Q20)o1;
Flat_Q20 f2 = (Flat_Q20)o2;
if(f1.getRate() > f2.getRate())
return 1;
else if(f1.getRate() < f2.getRate())
return -1;
else
return 0;
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 61

2630006 Programming Skills IV (Java)


}
22. Write a program that takes names of a text files as command line argument and searches the
files for occurence of palindromes. The output should print all the occurences of palindromes in the
file, with their filename and line numbers. The end of line in the file will be marked by the newline
character, '\n'. (A palindrome is a word which has the same spelling when read from left to right or
right to left). Use multithreading to process files in parallel.
import java.io.*;
public class P22
{
public static void main(String args[])
{
FileSearch fs;
for(int i=0;i<args.length;i++)
{
fs = new FileSearch(args[i]);
fs.start();
}
}
}
class FileSearch extends Thread
{
String filename;
FileSearch()
{
filename="palindrom.txt";
}
FileSearch(String file)
{
filename = file;
}
public void run()
{
try
{
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String line="",words[];
int c=0;
while((line=br.readLine())!=null)
{
c++;
words=line.split(" ");
for(int i=0;i<words.length;i++)
{
StringBuffer sb = new StringBuffer(words[i]);
sb = sb.reverse();
String rev = sb.toString();
if(words[i].equals(rev))
{
System.out.print("\nFile :"+filename+" Word="+words[i]+" Line="+c);
}
}
}
fr.close();
}
catch(Exception ex)
{
System.out.print(ex.toString());
}
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 62

2630006 Programming Skills IV (Java)

23. Create an applet named UnitConversion, which allows user to select a particular
conversion from following options.(Use list)
1. Decimal to HexaDecimal [Use Integer.toHexString()].
2. Decimal to Octal [Use Integer.toOctalString()].
3. Feet to Centimeter.(1 feet = 30.48cm)
4. Inches to Feet (1 feet = 12 inches)
Once user selects particular conversion then show the converted value with proper
formatted message. (Like if user selects Inches to Feet option and input value is 60
then message should be 60 inches is equal to 5 Feet.)
import java.awt.*;
import java.awt.event.*;
public class P23 extends Applet
{
Label l1,l2;
Button b1,b2,b3,b4;
TextField t1,t2;
String op;
public void init()
{
l1 = new Label("Input");
t1 = new TextField("100");
l2 = new Label("Output");
t2 = new TextField("0");
t2.setEditable(false);
b1
b2
b3
b4

=
=
=
=

new
new
new
new

Button("Dec->Hexa");
Button("Dec->Octal");
Button("Feet->CM");
Button("Inches->Feet");

setLayout(new GridLayout(4,2,5,5));
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(b2);
add(b3);
add(b4);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int ip = Integer.parseInt(t1.getText());
op = Integer.toHexString(ip);
t2.setText(op);
}
});

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 63

2630006 Programming Skills IV (Java)


b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int ip = Integer.parseInt(t1.getText());
op = Integer.toOctalString(ip);
t2.setText(op);
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
float feet = Float.parseFloat(t1.getText());
float cm = feet*30.48f;
t2.setText(String.valueOf(cm));
}
});
b4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
float inch = Float.parseFloat(t1.getText());
float feet = inch/12;
t2.setText(String.valueOf(feet));
}
});
}
}

24. Create a class called Statistical Data, which has capability of maintaining data
regarding multiplevariables. It should have a method to specify the variable names as
String array and the method to load values from a file regarding the variables. eg. We
consider two variables as percentage of
marks in GCET exam and percentage of marks in 1st year of MCA, Provide methods in
the class to compute the correlation coefficient between any two variables, specified in
the parameter. Test the class by computing the correlation coefficient between the
marks of GCET and marks of 1st year
MCA for students of your class.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 64

2630006 Programming Skills IV (Java)

class StatisticalData
{
int v1[],v2[];
String v1name,v2name;
public StatisticalData()
{
v1name=new String("str1");
v2name=new String();
v1=new int[5];
v2=new int[5];
v2name="str2";
}
public void get()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
System.out.println("Enter First variable name and its values: ");
try{
v1name = br.readLine();
for(i=0;i<5;i++)
{
v1[i]=Integer.parseInt(br.readLine());
}
System.out.println("Enter Second variable name and its values: ");
v2name = br.readLine();
for(i=0;i<5;i++)
{
v2[i]=Integer.parseInt(br.readLine());
}
}
catch(IOException e)
{
System.out.println("Error while Reading from console");
}
}
public void correl_coeff()
{
double d,m1=0,m2=0,tatb=0,sab,ta2=0,tb2=0,sa,sb,cor_coef;
int i;
System.out.printf("%s: ",v1name);
for(i=0;i<5;i++)
{
System.out.printf("%d ",v1[i]);
}
System.out.println();
System.out.printf("%s: ",v2name);
for(i=0;i<5;i++)
{
System.out.printf("%d ",v2[i]);
m1=m1+v1[i];
m2=m2+v2[i];
}
System.out.println();
m1=m1/5;
m2=m2/5;
for(i=0;i<5;i++)
{
tatb=tatb+(v1[i]-m1)*(v2[i]-m2);
ta2=ta2+(v1[i]-m1)*(v1[i]-m1);
tb2=tb2+(v2[i]-m2)*(v2[i]-m2);
}
sab=tatb/4;
sa=ta2/5;
sb=tb2/5;
sa=Math.sqrt(sa);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 65

2630006 Programming Skills IV (Java)


sb=Math.sqrt(sb);
cor_coef=sab/sa*sb;
System.out.println("correlation co-efficient: " + cor_coef);
}
}
class P24
{
public static void main(String args[])
{
StatisticalData x=new StatisticalData();
x.get();
x.correl_coeff();
}
}

25. Simple random sampling uses a sample of size n from a population fo size N to
obtain data that can be used to make inferences about the characteristics of a
population. Suppose that, from a population of 50 bank accounts, we want to take a
random sample of four accounts in order to
learn about the population. How many different random samples of four accounts are
possible.Write a Java class which can compute the number of random samples for size
n from a population of N, Also provide method to display all possible samples, and also
a method to return a sample,
derived from the possible samples. (Hint use random method of the Math class to select
the random sample).
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="prg5_25" width = 500 height=500>
</applet>
*/
public class prg5_25 extends Applet implements ActionListener
{
Label lno,lnm,lst,lplan,lsms,lcall,lhr,lmin,lsec,ltax,lext,lbill;
TextField tno,tnm,tsms,thr,tmin,tsec,ttax,tbill;
Choice cst;
CheckboxGroup cbg;
Checkbox gen,pre;
Checkbox gprs,gps,iwrld;
Button b1,b2;
TextArea ta;
public void init()
{
lno = new Label("Cell Number");
lnm = new Label("Customer Name");

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 66

2630006 Programming Skills IV (Java)


lst = new Label("State");
lplan = new Label("Bill Plan");
lsms = new Label("Total SMS");
lcall = new Label("Total Call");
lhr = new Label("Hours");
lmin = new Label("Miniute");
lsec = new Label("Second");
ltax = new Label("Tax");
lext = new Label("Extra Facilities");
lbill = new Label("Bill Amount");
tno = new TextField();
tnm = new TextField();
tsms = new TextField();
thr = new TextField();
tmin = new TextField();
tsec = new TextField();
ttax = new TextField();
tbill = new TextField();
tbill.setEditable(false);
cst = new Choice();
cst.add("Gujarat"); cst.add("JK"); cst.add("MP");
cst.add("AP"); cst.add("Goa"); cst.add("UP");
cbg = new CheckboxGroup();
gen = new Checkbox("General",cbg,true);
pre = new Checkbox("Premium",cbg,false);
gprs = new Checkbox("GPRS");
gps = new Checkbox("GPS");
iwrld = new Checkbox("i-World");
b1 = new Button("Display");
b1.addActionListener(this);
b2 = new Button("Reset");
b2.addActionListener(this);
ta = new TextArea();
setLayout(null);
lno.setBounds(10,10,100,20);
add(lno);
tno.setBounds(110,10,100,20);
add(tno);
lnm.setBounds(10,40,100,20);
add(lnm);
tnm.setBounds(110,40,150,20);
add(tnm);
lst.setBounds(250,10,80,20);
add(lst);
cst.setBounds(330,10,100,20);
add(cst);
lplan.setBounds(10,70,100,20);
add(lplan);
gen.setBounds(110,70,100,20);
add(gen);
pre.setBounds(210,70,100,20);
add(pre);
lsms.setBounds(10,100,100,20);
add(lsms);
tsms.setBounds(110,100,50,20);
add(tsms);
lcall.setBounds(10,130,100,20);
add(lcall);
thr.setBounds(110,130,50,20);
add(thr);
lhr.setBounds(160,130,50,20);
add(lhr);
tmin.setBounds(210,130,50,20);
add(tmin);
lmin.setBounds(260,130,50,20);
add(lmin);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 67

2630006 Programming Skills IV (Java)


tsec.setBounds(310,130,50,20);
add(tsec);
lsec.setBounds(360,130,50,20);
add(lsec);
ltax.setBounds(10,160,100,20);
add(ltax);
ttax.setBounds(110,160,50,20);
add(ttax);
lext.setBounds(10,190,100,20);
add(lext);
gprs.setBounds(110,190,80,20);
add(gprs);
gps.setBounds(190,190,80,20);
add(gps);
iwrld.setBounds(270,190,80,20);
add(iwrld);
b1.setBounds(50,220,100,20);
add(b1);
b2.setBounds(170,220,100,20);
add(b2);
lbill.setBounds(10,250,100,20);
add(lbill);
tbill.setBounds(110,250,100,20);
add(tbill);
ta.setBounds(10,280,400,200);
add(ta);
}
public void actionPerformed(ActionEvent ae)
{
String msg;
int cell,sms,hr,mn,sc,tx,flag;
cell = 0;
sms = 0;
hr = 0;
mn = 0;
sc = 0;
tx = 0;
flag = 0;
msg = "";
if( ae.getSource()==b1 )
{
if( tno.getText().equals("") ||tnm.getText().equals("") ||
tsms.getText().equals("") ||thr.getText().equals("")
||tmin.getText().equals("") ||tsec.getText().equals("")
||ttax.getText().equals("") )
{
ta.setText("Enter Values for each field\n");
}
else
{
try
{
cell = Integer.parseInt(tno.getText());
}
catch(Exception e)
{
msg = msg+"Invalid Cell Number\n";
flag = 1;
}
try
{
sms = Integer.parseInt(tsms.getText());
}
catch(Exception e)
{
msg = msg+"Invalid SMS Value\n";

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 68

2630006 Programming Skills IV (Java)


flag = 1;
}
try
{
hr = Integer.parseInt(thr.getText());
}
catch(Exception e)
{
msg = msg+"Invalid Hour Value\n";
flag = 1;
}
try
{
mn = Integer.parseInt(tmin.getText());
}
catch(Exception e)
{
msg = msg+"Invalid Miniue Value\n";
flag = 1;
}
try
{
sc = Integer.parseInt(tsec.getText());
}
catch(Exception e)
{
msg = msg+"Invalid Second Value\n";
flag = 1;
}
try
{
tx = Integer.parseInt(ttax.getText());
}
catch(Exception e)
{
msg = msg+"Invalid Tax Value\n";
flag = 1;
}
if( flag==0 )
{
double amt,genrs,prers,smsps,smsrs,scnd,callmn,
callps,callrs,taxrs,gprsrs,gpsrs,iwrldrs;
smsps = 0;
callps = 0;
smsrs = 0;
callrs = 0;
genrs = 0;
prers = 0;
gprsrs = 0;
gpsrs = 0;
iwrldrs = 0;
amt = 0;
msg = "Cell Number : "+tno.getText()+"\n";
msg = msg + "Customer Name : "+tnm.getText()+"\n";
msg = msg + "State : "+cst.getSelectedItem()+"\n";
msg = msg + "\nBilling Plan : ";
hr = hr*60;
mn = mn*1;
scnd = (double) sc/60;
callmn = hr+mn+scnd;
if( gen.getState() )
{
genrs = 200;
prers = 0;
msg = msg + gen.getLabel();
if( sms<100 )

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 69

2630006 Programming Skills IV (Java)


{
smsps = 0;
}
else
{
smsps = (sms-100)*0.1;
}
if( callmn<500 )
{
callps = 0;
}
else
{
callps = (callmn-500)*0.5;
}
}
if( pre.getState() )
{
genrs = 0;
prers = 500;
msg = msg + pre.getLabel();
if( sms<500 )
{
smsps = 0;
}
else
{
smsps = (sms-100)*0.05;
}
if( callmn<1000 )
{
callps = 0;
}
else
{
callps = (callmn-500)*0.3;
}
}
smsrs = smsps/100;
callrs = callps/100;
taxrs = (double) tx;
msg = msg + "\n\n";
msg = msg + "Extra Facility : ";
if( gprs.getState() )
{
gprsrs = 100;
msg = msg + gprs.getLabel()+", ";
}
if( gps.getState() )
{
gpsrs = 200;
msg = msg + gps.getLabel()+", ";
}
if( iwrld.getState() )
{
iwrldrs = 150;
msg = msg + iwrld.getLabel()+".";
}
amt = genrs + prers + smsrs + callrs + taxrs + gprsrs+ gpsrs + iwrldrs;
msg = msg + "\n\n";
msg = msg + "Bill Amount : " + amt;
tbill.setText(""+amt);
}
ta.setText(msg);
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 70

2630006 Programming Skills IV (Java)


if( ae.getSource()==b2 )
{
tno.setText("");
tnm.setText("");
tsms.setText("");
thr.setText("");
tmin.setText("");
tsec.setText("");
ttax.setText("");
tbill.setText("");
}
}
}
28.Write an application to convert digits into words, use appropriate structures available from
java.util package.
import java.util.*;
import java.io.*;
public class P28
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
List <String> l1; // 0 to 9;
List <String> l2; // 11 to 19;
List <String> l3; // 20 to 90;
List <String> l4; // 100, 1000, 10000....
public P28()
{
try
{
init();
System.out.print("");
System.out.print("\nEnter Number : ");
System.out.print("");
n = Integer.parseInt(br.readLine());
if(n>=0 && n<10)
{
System.out.print(l1.get(n));
}
else if(n>=11 && n<20)
{
System.out.print(l2.get(n-11));
}
else if(n>20 && n<100)
{
int d1 = n%10;
n = n/10;
int d2 = n%10;
System.out.print(l3.get(d2-2)+" "+l1.get(d1));
}
else if(n>=100 && n<1000)
{
int d1 = n%10;
n = n/10;
int d2 = n%10;
n = n/10;
int d3 = n%10;
if(d1==0 && d2==0)
System.out.print(l1.get(d3)+" "+l4.get(0));
else if(d2==0)
System.out.print(l1.get(d3)+" "+l4.get(0)+l1.get(d1));
else
System.out.print(l1.get(d3)+" "+l4.get(0)+" "+l3.get(d2-2)+" "+l1.get(d1));

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 71

2630006 Programming Skills IV (Java)

}
}
catch(Exception ex)
{
System.out.print(ex);
}
}
public void init()
{
l1 = new ArrayList<String>();
l2 = new ArrayList<String>();
l3 = new ArrayList<String>();
l4 = new ArrayList<String>();
l1.add("zero");
l1.add("one");
l1.add("two");
l1.add("three");
l1.add("four");
l1.add("five");
l1.add("six");
l1.add("seven");
l1.add("eight");
l1.add("nine");
l2.add("eleven");
l2.add("tweleve");
l2.add("therteen");
l2.add("fourteeh");
l2.add("fifteen");
l2.add("sixteen");
l2.add("seventeen");
l2.add("eighteen");
l2.add("nineteen");
l3.add("twenty");
l3.add("thirty");
l3.add("fourty");
l3.add("fifty");
l3.add("sixty");
l3.add("seventy");
l3.add("eighty");
l3.add("ninety");
l4.add("hundreds");
l4.add("thousands");
l4.add("lakhs");
l4.add("crores");
}
public static void main(String args[])
{
new P28();
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 72

2630006 Programming Skills IV (Java)


29. An educational institution wishes to maintain a database of its employees. The database is
divided into a number of classes whose hierarchical relationships are as follows:
Staff (code, name) is the base class, which in turn has teacher (subject, publication), typist
(speed) and officer (grade) as its child classes. The typist again has regular ( ) and causal (daily
Wages) as its child classes. Note that the information given in brackets specifies the minimum
information required for each class. Specify all classes and define functions to create the database
and retrieve information as and when needed.
import java.io.*;
class P29
{
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
System.out.print("1. Staff Registration");
System.out.print("\n2. Staff Details");
System.out.print("\n3. Quit");
System.out.print("\nEnter choice : ");
int ch1=Integer.parseInt(br.readLine());
if(ch1==1)
{
while(true)
{
System.out.print("\nStaff Registration");
System.out.print("\n===============");
System.out.print("\n1. Teacher");
System.out.print("\n2. Officer");
System.out.print("\n3. Typist");
System.out.print("\n4 Quit");
System.out.print("Enter choice : ");
int ch2 = Integer.parseInt(br.readLine());
switch(ch2)
{
case 1 :
{
Teacher t = new Teacher();
t.get();
t.dataWriter();
break;
}
case 2 :
{
Officer o = new Officer();
o.get();
o.dataWriter();
break;
}
case 3 :
{
int ch4;
do
{
System.out.print("\nStaff Registration");
System.out.print("\n===============");
System.out.print("\n1. Regular");
System.out.print("\n2. Casual");
System.out.print("\n3. Done");
System.out.print("\nEnter choice : ");
ch4 = Integer.parseInt(br.readLine());
if(ch4 == 1)
{
Regular r = new Regular();
r.get();
r.dataWriter();

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 73

2630006 Programming Skills IV (Java)


}
else if(ch4 == 2)
{
Casual c = new Casual();
c.get();
c.dataWriter();
}
else
{
System.out.print("Invalid Choice!!!...");
}
}while(ch4 >0 && ch4 <3);
break;
}
case 4:
{
System.exit(1);
}
}//switch case
}//inner while
}//end of if...
else if(ch1==2)
{
while(true)
{
System.out.print("\nStaff Details");
System.out.print("\n===============");
System.out.print("\n1. Teacher");
System.out.print("\n2. Officer");
System.out.print("\n3. Typist");
System.out.print("\n4 Quit");
System.out.print("\nEnter choice : ");
int ch3 = Integer.parseInt(br.readLine());
switch(ch3)
{
case 1 :
{
Teacher t = new Teacher();
t.dataReader();
break;
}
case 2 :
{
Officer o = new Officer();
o.dataReader();
break;
}
case 3 :
{
int ch5;
do
{
System.out.print("\nStaff Registration");
System.out.print("\n===============");
System.out.print("\n1. Regular");
System.out.print("\n2. Casual");
System.out.print("\n3. Done");
System.out.print("\nEnter choice : ");
ch5 = Integer.parseInt(br.readLine());
if(ch5 == 1)
{
Regular r = new Regular();
r.dataReader();
}
else if(ch5 == 2)
{

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 74

2630006 Programming Skills IV (Java)


Casual c = new Casual();
c.dataReader();
}
else
{
System.out.print("Invalid Choice!!!...");
}
}while(ch5 >0 && ch5 <3);
break;
}
case 4:
{
System.exit(1);
}
}//switch case
}//inner while
}//end of else if
else
{
System.exit(1);
}
}//outer while loop
}
}
//import java.io.*;
class Regular extends Typist
{
double wages;
public Regular()
{
wages=100;
}
public Regular(int code,String name,int speed,double s)
{
super(code,name,speed);
wages=s;
}
public void get() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
super.get();
System.out.print("\n Enter wages : ");
wages=Double.parseDouble(br.readLine());
}
public void display()
{
System.out.print("\n Employee Code : " + getCode());
System.out.print("\n Employee Name : " + getName());
System.out.print("\n Typing Speed
: " + getSpeed());
System.out.print("\n Regular wages
: " + wages);
}
public void dataWriter()
{
try
{
String str = new String(getCode() + " | " + getName() + " | " + getSpeed() +" | "+ wages +
"\n");
FileWriter fw = new FileWriter("regular.txt",true);
fw.write(13);
fw.write(10);
fw.write(str , 0 , str.length());
fw.close();
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 75

2630006 Programming Skills IV (Java)


catch(Exception e)
{
System.out.print(e.getMessage());
}
}
public void dataReader()
{
try
{
FileReader fr = new FileReader("regular.txt");
BufferedReader br = new BufferedReader(fr); // fetches line by line from file
String str = new String();
while((str=br.readLine()) != null)
{
System.out.print(str + "\n");
}
fr.close();
}
catch(Exception e)
{
System.out.print("\n\n\t\t\t " + e.getMessage());
}
}
}
//import java.io.*;
class Casual extends Typist
{
double salary;
public Casual()
{
salary=100;
}
public Casual(int code,String name,int speed,double s)
{
super(code,name,speed);
salary=s;
}
public void get() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
super.get();
System.out.print("\n Enter Salary : ");
salary=Double.parseDouble(br.readLine());
}
public void display()
{
System.out.print("\n Employee Code : " + getCode());
System.out.print("\n Employee Name : " + getName());
System.out.print("\n Typing Speed
: " + getSpeed());
System.out.print("\n Casual Salary
: " + salary);
}
public void dataWriter()
{
try
{
String str = new String(getCode() + " | " + getName() + " | " + getSpeed() +" | "+ salary +
"\n");
FileWriter fw = new FileWriter("casual.txt",true);
fw.write(13);
fw.write(10);
fw.write(str , 0 , str.length());
fw.close();
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 76

2630006 Programming Skills IV (Java)


catch(Exception e)
{
System.out.print(e.getMessage());
}
}
public void dataReader()
{
try
{
FileReader fr = new FileReader("casual.txt");
BufferedReader br = new BufferedReader(fr); // fetches line by line from file
String str = new String();
while((str=br.readLine()) != null)
{
System.out.print(str + "\n");
}
fr.close();
}
catch(Exception e)
{
System.out.print("\n\n\t\t\t " + e.getMessage());
}
}
}
//import java.io.*;
class Officer extends Staff
{
char grade;
public Officer()
{
grade='A';
}
public Officer(int code,String name,char s)
{
super(code,name);
grade=s;
}
public char getgrade()
{
return grade;
}
public void get() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
super.get();
System.out.println("\n\n Enter Grade : ");
grade=br.readLine().charAt(0);
}
public void display()
{
System.out.print("\n\n Employee Code : " + getCode());
System.out.print("\n\n Employee Name : " + getName());
System.out.print("\n\n Officer grade
: " + grade);
}
public void dataWriter()
{
try
{
String str = new String(getCode() + " | " + getName() + " | " + grade + "\n");
FileWriter fw = new FileWriter("officer.txt",true);
fw.write(13);
fw.write(10);
fw.write(str , 0 , str.length());
fw.close();
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 77

2630006 Programming Skills IV (Java)


catch(Exception e)
{
System.out.print(e.getMessage());
}
}
public void dataReader()
{
try
{
FileReader fr = new FileReader("officer.txt");
BufferedReader br = new BufferedReader(fr); // fetches line by line from file
String str = new String();
while((str=br.readLine()) != null)
{
System.out.print(str + "\n");
}
fr.close();
}
catch(Exception e)
{
System.out.print("\n\n\t\t\t " + e.getMessage());
}
}
}
//import java.io.*;
abstract class Staff
{
private int code;
private String nm;
public Staff()
{
code = 0;
nm = new String("");
}
public Staff(int no,String name)
{
code = no;
nm = name;
}
public int getCode()
{
return code;
}
public String getName()
{
return nm;
}
public void get() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n\n Enter Employee code : ");
code=Integer.parseInt(br.readLine());
System.out.println("\n\n Enter Employee Name : ");
nm=br.readLine();
}
public abstract void display();
public abstract void dataWriter();
public abstract void dataReader();
}
//import java.io.*;
class Teacher extends Staff
{
private String sub,pub;
public Teacher()

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 78

2630006 Programming Skills IV (Java)


{
sub=pub="";
}
public Teacher(int code,String name,String no,String nm)
{
super(code,name);
sub = no;
pub = nm;
}
public void get() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
super.get();
System.out.println("\n\n Enter Subject name : ");
sub=br.readLine();
System.out.println("\n\n Enter Publication Name : ");
pub=br.readLine();
}
public void display()
{
System.out.print("\n\n Employee Code : " + getCode());
System.out.print("\n\n Employee Name : " + getName());
System.out.print("\n\n Subject
: " + sub);
System.out.print("\n\n Publication
: " + pub);
}
public void dataWriter()
{
try
{
String str = new String(getCode() + " | " + getName() + " | " + sub + " | " + pub + "\n");
FileWriter fw = new FileWriter("teacher.txt",true);
fw.write(13);
fw.write(10);
fw.write(str , 0 , str.length());
fw.close();
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
public void dataReader()
{
try
{
FileReader fr = new FileReader("teacher.txt");
BufferedReader br = new BufferedReader(fr); // fetches line by line from file
String str = new String();
while((str=br.readLine()) != null)
{
System.out.print(str + "\n");
}
fr.close();
}
catch(Exception e)
{
System.out.print("\n\n\t\t\t " + e.getMessage());
}
}
}
//import java.io.*;
class Typist extends Staff
{
int speed;
public Typist()

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 79

2630006 Programming Skills IV (Java)


{
speed=10;
}
public Typist(int code,String name,int s)
{
super(code,name);
speed=s;
}
public int getSpeed()
{
return speed;
}
public void get() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
super.get();
System.out.println("\n Enter Typing Speed : ");
speed=Integer.parseInt(br.readLine());
}
public void display()
{}
public void dataWriter()
{
}
public void dataReader()
{
}
}

30. shape, a public abstract method to compute the area of the shape, and a public
abstract method paint() to draw the shape on a Graphics object, which is passed as
parameter. Derive subclasses for Point, Line, Circle and Rectangle. You can represent
a line as two points, a circle as a centerPoint and a radius, and
a Rectangle as two points on diagonally opposite corners. Now define a class called
DrawingBoard, which extends the Canvas class and maintains instances of the Shape
objects in a List, also oerrides the paint method to draw the Shape instances
maintained in the List,

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 80

2630006 Programming Skills IV (Java)

/* <applet code="P30" width=800 height=600></applet> */


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
abstract class Shape
{
int x,y;
Shape()
{
x=0;
y=0;
}
Shape(int x,int y)
{
this.x=x;
this.y=y;
}
public abstract double area();
public abstract void paint(Graphics g);
}
class Line extends Shape
{
int x1,y1;
Line()
{
}
Line(int x,int y,int x1,int y1)
{
super(x,y);
this.x1=x1;
this.y1=y1;
}
public double area()
{
return 0.0;
}
public void paint(Graphics g)
{
g.drawLine(x,y,x1,y1);
}
}
class Circle extends Shape
{
int r;
Circle()
{
x=100;
y=100;
r=100;
}
Circle(int x,int y,int r)
{
super(x,y);
this.r=r;
}
public double area()
{
return Math.PI*r*r;
}
public void paint(Graphics g)
{

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 81

2630006 Programming Skills IV (Java)


g.drawOval(x-r/2,y-r/2,r,r);
}
}
class Rectangle extends Shape
{
int x1,y1;
Rectangle()
{
}
Rectangle(int x,int y,int x1,int y1)
{
super(x,y);
this.x1=x1;
this.y1=y1;
}
public double area()
{
return x1*y1;
}
public void paint(Graphics g)
{
g.drawRect(x,y,x1,y1);
}
}
public class P30 extends Applet
{
Line l;
Circle c;
Rectangle r;
double a1,a2;
public void init()
{
l = new Line(100,100,300,300);
c = new Circle(100,350,100);
r = new Rectangle(200,100,100,100);
a1 = c.area();
a2 = r.area();
}
public void paint(Graphics g)
{
l.paint(g);
c.paint(g);
r.paint(g);
g.drawString("Area of Circle is "+String.valueOf(a1),200,50);
g.drawString("Area of Rectangle is "+String.valueOf(a2),200,75);
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 82

2630006 Programming Skills IV (Java)

List-2
1.Write a JAVA program which performs the following listed operations:
A.Create a package named MyPackage which consists of following classes
1. A class named Student which stores information like the roll number, first name, middle name,
last name, address and age of the student. The class should also contain appropriate get and set
methods.
2. A class named AddStudentFrame which displays a frame consisting of appropriate controls to
enter the details of a student and store these details in the Student class object. The frame should
also have two buttons with the caption as Add Record and Search Record.
3. A class named MyCustomListener which should work as a user defined event listener to handle
required events as mentioned in following points.
B.The Add record button should add the record entered in the frame controls to a pre defined
file.
C.Provide a menu on the AddStudentFrame which has menu items titled, Set the record file and
Exit.
1. When the Set the record file menu item is clicked, the user should be asked to input the
complete path of the file where he desires to save the records.
2. When the Exit menu item is clicked, the frame should be closed.[Note: Use the
MyCustomListener class only to handle the appropriate events]
D.1. The Search record button should open a new frame which should take input of search
criteria using a radio button. The radio button should provide facility to search on basis of first
name, middle name or last name.
2. The new frame should also have a text box to input the search criteria value.
3. The search result should be displayed in a proper format on the same frame in a text area. [The
records should be searched from the pre defined file which consists all saved records][Note: Use
the MyCustomListener class only to handle the appropriate events]

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 83

2630006 Programming Skills IV (Java)


E.Provide proper error messages and perform appropriate exceptions where ever required in all the
classes

package MyPackage;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
//import MyPackage.*;
public class AddStudentFrame extends Frame implements ActionListener, WindowListener
{
Label lblroll;
Label lblfirst;
Label lbllast;
Label lblstatus;
Label lblmsg;
TextField tfroll;
TextField tffirst;
TextField tflast;
Button b,b1;
Student st;
public AddStudentFrame()
{
st = new Student();
setLayout(new FlowLayout());
lblroll = new Label("Roll No: ");
add(lblroll);
tfroll = new TextField(30);
add(tfroll);
lblfirst = new Label("First Name");
add(lblfirst);
tffirst = new TextField(30);
add(tffirst);
lbllast = new Label("Last Name");
add(lbllast);
tflast = new TextField(30);
add(tflast);
b = new Button("Save");
add(b);
b.addActionListener(this);
b1 = new Button("Search");
add(b1);
b1.addActionListener(this);
lblmsg = new Label(" ");
add(lblmsg);
lblstatus = new Label(" ");
add(lblstatus);
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu a = new Menu("File");
mb.add (a);
MenuItem a1 = new MenuItem("Exit");
a1.addActionListener(this);
a.add(a1);
Menu b = new Menu("Color");
mb.add (b);
MenuItem c1 = new MenuItem("Red");
c1.addActionListener(this);
b.add(c1);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 84

2630006 Programming Skills IV (Java)


MenuItem c2 = new MenuItem("Green");
c2.addActionListener(this);
b.add(c2);
MenuItem c3 = new MenuItem("Blue");
c3.addActionListener(this);
b.add(c3);
setTitle("Welcome tO Program 1 About Student Management");
setSize(360, 420);
setVisible(true);
}
public void windowActivated(WindowEvent we) {}
public void windowDeactivated(WindowEvent we) {}
public void windowClosing(WindowEvent we) {}
public void windowDeiconified(WindowEvent we) {}
public void windowIconified(WindowEvent we) {}
public void windowOpened(WindowEvent we) {}
public void windowClosed(WindowEvent we) {}
public void actionPerformed(ActionEvent evt)
{
String str = evt.getActionCommand();
if(str.equals("Save"))
{
try
{
int r = Integer.parseInt(tfroll.getText());
st.setstudent(r, tffirst.getText(), "", tflast.getText(),
"Baroda");
lblmsg.setText("Record Saved. ");
MyCustomListener m = new MyCustomListener();
m.setdata(str,st.getname());
}catch(Exception e)
{
lblmsg.setText(e.getMessage());
}
}
else if(str.equals("Search"))
{
try
{
String fullname;
//fullname = st.getname();
MyCustomListener m = new MyCustomListener();
fullname = m.getdata(str,tfroll.getText());
if (fullname == "Not Found")
lblmsg.setText("Record Not Found !");
else
lblmsg.setText("Welcome.. " + fullname);
}catch(Exception e)
{
lblmsg.setText("Sorry.. Record Not Saved !");
}
}
else if (str.equals("Exit"))
{
System.exit(0);
}
else if(str.equals("Red"))
{
//setColor(Color.Red);
}
}
public static void main(String[] args) {
AddStudentFrame t = new AddStudentFrame();
}
}
class Student

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 85

2630006 Programming Skills IV (Java)


{
int roll;
String first_name;
String middle_name;
String last_name;
String address;
int age;
Student()
{
roll=0;
first_name="";
middle_name="";
last_name="";
address="";
}
public void setstudent(int r, String fn, String mn, String ln, String ad)
{
try
{
roll=r;
first_name=fn;
middle_name=mn;
last_name=ln;
address=ad;
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getname()
{
return(roll +"," + first_name + "," + last_name);
}
}
class MyCustomListener
{
MyCustomListener()
{}
public void setdata(String str,String val)
{
if(str.equals("Save"))
{
try
{
String commaSeparated = getdata("All","");
if ( commaSeparated.length() > 0 )
{
commaSeparated = commaSeparated + "," + val;
}
else
{
commaSeparated = commaSeparated + val;
}
File f = new File("f1.txt");
FileWriter fw = new FileWriter(f);
fw.write(commaSeparated);
fw.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static String getdata(String str,String val)
{
String t;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 86

2630006 Programming Skills IV (Java)


t = "";
if(str.equals("All"))
{
try
{
File f = new File("f1.txt");
FileReader fr = new FileReader(f);
int i;
while ( (i = fr.read() ) != -1 )
{
t = t + (char)i;
}
fr.close();
return t;
}catch(Exception e)
{
}
}
else if(str.equals("Search"))
{
try
{
File f = new File("f1.txt");
FileReader fr = new FileReader(f);
int i;
while ( (i = fr.read() ) != -1 )
{
t = t + (char)i;
}
fr.close();
String [] items = t.split(",");
for (int j = 0; j < items.length; j++)
{
if( items[j].equals(val) )
{
return items[j+1] + " " + items[j+2];
}
}
}catch(Exception e)
{
//lblmsg.setText("Sorry.. Record Not Saved !");
return "Not Found";
}
}
return "Not Found";
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 87

2630006 Programming Skills IV (Java)

12.Write a JAVA program which performs the following listed operations:


A.Create a package named MyPackage which consists of following classes
1. A class named Course which stores information like the Course no, Course name,
Max_Marks, Pass_Marks. The class should also contain appropriate get and set methods.
2. A class named AddCourseFrame which displays a frame consisting of appropriate
controls to enter the details of a Course and store these details in the Course class
object. The frame should also have two buttons with the caption as Add Record and
Search Record.
3. A class named MyCustomListener which should work as a user defined event
listener to handle required events as mentioned in following points.
B The Add record button should add the record entered in the frame controls to a pre
defined file.
C Provide a menu on the AddCourseFrame which has menu items titled, Set the record
file and Exit.
1. When the Set the record file menu item is clicked, the user should be asked to
input the complete path of the file where he desires to save the records.
2. When the Exit menu item is clicked, the frame should be closed.
[Note: Use the MyCustomListener class only to handle the appropriate events]
D-1. The Search record button should open a new frame which should take input of
search criteria using a radio button. The radio button should provide facility to search
on basis of course name.
2. The new frame should also have a text box to input the search criteria value.
3. The search result should be displayed in a proper format on the same frame in a text
area. [The records should be searched from the pre defined file which consists all
saved records][Note: Use the MyCustomListener class only to handle the appropriate
events]
E.Provide proper error messages and perform appropriate exceptions where ever
required in all the classes
package MyPackage;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
//import MyPackage.*;
public class AddCourseFrame extends Frame implements ActionListener, WindowListener
{
Label lblcurno;
Label lblcurnm;
Label lblmaxm;
Label lblpassm;
Label lblmsg;
TextField tfcurno;
TextField tfcurnm;
TextField tfmaxm;
TextField tfpassm;
Button b,b1;
Student st;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 88

2630006 Programming Skills IV (Java)


Label lblstatus;
public AddCourseFrame()
{
st = new Student();
setLayout(new FlowLayout());
lblcurno = new Label("Course No: ");
add(lblcurno);
tfcurno = new TextField(30);
add(tfcurno);
lblcurnm = new Label("Course Name");
add(lblcurnm);
tfcurnm = new TextField(30);
add(tfcurnm);
lblmaxm = new Label("Max Marks");
add(lblmaxm);
tfmaxm = new TextField(30);
add(tfmaxm);
lblpassm = new Label("Pass Marks");
add(lblpassm);
tfpassm = new TextField(30);
add(tfpassm);
b = new Button("Save");
add(b);
b.addActionListener(this);
b1 = new Button("Search");
add(b1);
b1.addActionListener(this);
lblmsg = new Label(" ");
add(lblmsg);
lblstatus = new Label( ");
add(lblstatus);
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu a = new Menu("Set Record File");
mb.add (a);
MenuItem a1 = new MenuItem("Exit");
a1.addActionListener(this);
a.add(a1);
Menu b = new Menu("Exit");
b.addActionListener(this);
mb.add (b);
setTitle("Welcome tO Program 1 About Student Management");
setSize(360, 420);
setVisible(true);
}
public
public
public
public
public
public

void
void
void
void
void
void

windowActivated(WindowEvent we) {}
windowDeactivated(WindowEvent we) {}
windowClosing(WindowEvent we) {}
windowDeiconified(WindowEvent we) {}
windowIconified(WindowEvent we) {}
windowOpened(WindowEvent we) {}

public void windowClosed(WindowEvent we) {}


public void actionPerformed(ActionEvent evt)
{
String str = evt.getActionCommand();
if(str.equals("Save"))
{
try
{

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 89

2630006 Programming Skills IV (Java)


int r = Integer.parseInt(tfcurno.getText());
int mm = Integer.parseInt(tfmaxm.getText());
int pm = Integer.parseInt(tfpassm.getText());
st.setstudent(r,tfcurnm.getText(),mm,pm);
lblmsg.setText("Record Saved. ");
MyCustomListener m = new MyCustomListener();
m.setdata(str,st.getname());
}catch(Exception e)
{
lblmsg.setText(e.getMessage());
}
}
else if(str.equals("Search"))
{
try
{
String fullname;
//fullname = st.getname();
MyCustomListener m = new MyCustomListener();
fullname = m.getdata(str,tfcurno.getText());
if (fullname == "Not Found")
lblmsg.setText("Record Not Found !");
else
lblmsg.setText("Welcome.. " + fullname);
}catch(Exception e)
{
lblmsg.setText("Sorry.. Record Not Saved !");
}
}
else if (str.equals("Exit"))
{
System.exit(0);
}
else if(str.equals("Red"))
{
//setColor(Color.Red);
}
}
public static void main(String[] args) {
AddCourseFrame t = new AddCourseFrame();
}
}
class Student
{
int curno;
String cur_name;
int maxm;
int passm;
Student()
{
curno=0;
cur_name="";
maxm=0;
passm=0;
}
public void setstudent(int r, String cn, int mm, int pm)
{
try
{
curno=r;
cur_name=cn;
maxm=mm;

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 90

2630006 Programming Skills IV (Java)


passm=pm;
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getname()
{
return(curno +"," + cur_name + "," + maxm + "," + passm);
}
}
class MyCustomListener
{
MyCustomListener()
{
}
public void setdata(String str,String val)
{
if(str.equals("Save"))
{
try {
String commaSeparated = getdata("All","");
if ( commaSeparated.length() > 0 )
{
commaSeparated = commaSeparated + "," + val;
}
else
{
commaSeparated = commaSeparated + val;
}
File f = new File("cur.txt");
FileWriter fw = new FileWriter(f);
fw.write(commaSeparated);
fw.close();
//Code to Save Data to File
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static String getdata(String str,String val)
{
String t;
t = "";
if(str.equals("All"))
{
try
{
File f = new File("cur.txt");
FileReader fr = new FileReader(f);
int i;
while ( (i = fr.read() ) != -1 )
{
t = t + (char)i;
}
fr.close();

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 91

2630006 Programming Skills IV (Java)

return t;
}catch(Exception e)
{
}
}
else if(str.equals("Search"))
{
try
{
File f = new File("cur.txt");
FileReader fr = new FileReader(f);
int i;
while ( (i = fr.read() ) != -1 )
{
t = t + (char)i;
}
fr.close();
String [] items = t.split(",");
for (int j = 0; j < items.length; j++)
{
if( items[j].equals(val) )
{
return items[j+1] + " " + items[j+2];
}
}
}catch(Exception e)
{
return "Not Found";
}
}
return "Not Found";
}
}

25.Write a JAVA program which performs the following listed operations:


A.Create a package named MyPackage which consists of following classes
1. A class named Boat which stores information like Boat Id, Boat Name, Boat Color,
Price. The class should also contain appropriate get and set methods.
2. A class named AddBoatFrame which displays a frame consisting of appropriate
controls to enter the details of a Boat and store these details in the Boat class object.
The frame should also have three buttons with the caption as Add Record and Delete
Record and Exit.
3. A class named MyCustomListener which should work as a user defined event
listener to handle required events as mentioned in following points.
B-1. When the Add Record button is clicked, the dialog box should be appeared with
asking the user Do you really want to add record in the file. If the user selects Yes
than the record should be saved in the file.
2. When the Exit button is clicked, the frame should be closed.
[Note: Use the MyCustomListener class only to handle the appropriate events]
C-1. The Delete Record button should open a new frame which should take input of
delete criteria using a radio button. The radio button should provide facility to delete
on basis of Boat Name.

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 92

2630006 Programming Skills IV (Java)


2. The new frame should also have a text box to input the delete criteria value.
3. The record should be deleted from the file and a message dialog should appear with
the message that Record is successfully deleted.[Note: Use the MyCustomListener
class only to handle the appropriate events]
D.Provide proper error messages and perform appropriate exceptions where ever
required in all the classes
package MyPackage;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AddBoatFrame extends Frame implements ActionListener, WindowListener
{
Label lblbid;
Label lblbnm;
Label lblbclr;
Label lblbprice;
Label lblmsg;
TextField tfbid;
TextField tfbnm;
TextField tfbclr;
TextField tfbprice;
Button b,b1,b2;
Student st;
Label lblstatus;

public AddBoatFrame()
{
st = new Student();
setLayout(new FlowLayout());
lblbid = new Label("Boat Id: ");
add(lblbid);
tfbid = new TextField(30);
add(tfbid);
lblbnm = new Label("Boat Name");
add(lblbnm);
tfbnm = new TextField(30);
add(tfbnm);
lblbclr = new Label("Boat Color");
add(lblbclr);
tfbclr = new TextField(30);
add(tfbclr);
lblbprice = new Label("Boat Price");
add(lblbprice);
tfbprice = new TextField(30);
add(tfbprice);
b = new Button("Save");
add(b);
b.addActionListener(this);
b1 = new Button("Delete");
add(b1);
b1.addActionListener(this);
b2 = new Button("Exit");
add(b2);
b2.addActionListener(this);
lblmsg = new Label(" ");
add(lblmsg);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 93

2630006 Programming Skills IV (Java)


lblstatus = new Label(
add(lblstatus);

");

MenuBar mb = new MenuBar();


setMenuBar(mb);
Menu a = new Menu("");
mb.add (a);
MenuItem a1 = new MenuItem("");
a1.addActionListener(this);
a.add(a1);
Menu b = new Menu("");
b.addActionListener(this);
mb.add (b);
setTitle("Welcome tO Program 1 About Student Management");
setSize(360, 420);
setVisible(true);
}
public
public
public
public
public
public
public

void
void
void
void
void
void
void

windowActivated(WindowEvent we) {}
windowDeactivated(WindowEvent we) {}
windowClosing(WindowEvent we) {}
windowDeiconified(WindowEvent we) {}
windowIconified(WindowEvent we) {}
windowOpened(WindowEvent we) {}
windowClosed(WindowEvent we) {}

public void actionPerformed(ActionEvent evt)


{
String str = evt.getActionCommand();
if(str.equals("Save"))
{
try
{
int r = Integer.parseInt(tfbid.getText());
int mm = Integer.parseInt(tfbprice.getText());
//int pm = Integer.parseInt(tfpassm.getText());
st.setstudent(r,tfbnm.getText(),tfbclr.getText(),mm);
lblmsg.setText("Record Saved. ");
MyCustomListener m = new MyCustomListener();
m.setdata(str,st.getname());
}catch(Exception e)
{
lblmsg.setText(e.getMessage());
}
}
else if(str.equals("Delete"))
{
try
{
String fullname;
MyCustomListener m = new MyCustomListener();
fullname = m.getdata(str,tfbid.getText());
if (fullname == "Not Found")
lblmsg.setText("Record Not Found !");
else
lblmsg.setText("Delete" + fullname);

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 94

2630006 Programming Skills IV (Java)

}catch(Exception e)
{
lblmsg.setText("Sorry.. Record Not Saved !");
}
}
else if (str.equals("Exit"))
{
System.exit(0);
}
else if(str.equals("Red"))
{
}
}
public static void main(String[] args)
{
AddBoatFrame t = new AddBoatFrame();
}
}
class Student
{
int bid;
String boat_name;
String bclr;
int bprice;
Student()
{
bid=0;
boat_name="";
bclr="";
bprice=0;
}
public void setstudent(int r, String bn, String bc , int mm)
{
try
{
bid=r;
boat_name=bn;
bclr=bc;
bprice=mm;
//address=ad;
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getname()
{
return(bid +"," + boat_name + "," + bclr + "," + bprice);
}
}
class MyCustomListener
{
MyCustomListener()
{
}
public void setdata(String str,String val)
{
if(str.equals("Save"))
{

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 95

2630006 Programming Skills IV (Java)


try {
String commaSeparated = getdata("All","");
{
commaSeparated = commaSeparated + "," + val;
}
else
{
commaSeparated = commaSeparated + val;
}
File f = new File("Boat.txt");
FileWriter fw = new FileWriter(f);
fw.write(commaSeparated);
fw.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static String getdata(String str,String val)
{
String t;
t = "";
if(str.equals("All"))
{
try
{
File f = new File("Boat.txt");
FileReader fr = new FileReader(f);
int i;
while ( (i = fr.read() ) != -1 )
{
t = t + (char)i;
}
fr.close();
return t;
}catch(Exception e)
{
}
}
else if(str.equals("Delete"))
{
try
{
File f = new File("Boat.txt");
FileReader fr = new FileReader(f);
int i;
while ( (i = fr.read() ) != -1 )
{
t = t + (char)i;
}
fr.close();
String [] items = t.split(",");
for (int j = 0; j < items.length; j++)
{
if( items[j].equals(val) )
{
return items[j+1] + " " + items[j+2];
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 96

2630006 Programming Skills IV (Java)


}catch(Exception e)
{
return "Not Found";
}
}
return "Not Found";
}
}

Enrolment No: 145253693056

Name: Pandya Meet Pankajkumar 97

Você também pode gostar