PATEL GROUP OF INSTITUTIONS

advertisement
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
(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.*;
import javax.swing.*;//JOptionPane;
import java.util.Scanner;
import java.lang.String;
class info
{
int tcode[];
String tname[];
int seat[];
int price[];
info()
{
tcode=new int[5];
tcode[0]=101;
tcode[1]=102;
tcode[2]=103;
tcode[3]=104;
tcode[4]=105;
seat=new int[5];
seat[0]=5000;
seat[1]=1000;
seat[2]=2500;
seat[3]=1500;
seat[4]=3000;
price=new int[5];
price[0]=100;
price[1]=200;
price[2]=250;
price[3]=150;
price[4]=300;
tname=new String[5];
tname[0]="GANDHI EXPRESS";
tname[1]="RAJDHANI EXPRESS";
tname[2]="SABARMATI EXPRESS";
tname[3]="DILHI EXPRESS";
tname[4]="BOMBAY EXPRESS";
}
void put_info()
{
try
{
System.out.println();
System.out.println("\n\n\t\t~:INDIAN RAILWAY INFORMATION:~\n");
System.out.println("-------------------------------------------------------------------");
System.out.println(" NO" + "\tNAME OF RAILWAY" +"\t\tTIME"+"\t\tSEATS"+"\tPRICE");
System.out.println("-------------------------------------------------------------------");
System.out.println(" "+tcode[0]+"\t"+tname[0]+"\t\t08:15 A.M"+"\t"+seat[0]+"\t"+price[0]);
System.out.println(" "+tcode[1]+"\t"+tname[1]+"\t12:15 P.M"+"\t"+seat[1]+"\t"+price[1]);
System.out.println(" "+tcode[2]+"\t"+tname[2]+"\t14:25 P.M"+"\t"+seat[2]+"\t"+price[2]);
System.out.println(" "+tcode[3]+"\t"+tname[3]+"\t\t19:30 P.M"+"\t"+seat[3]+"\t"+price[3]);
System.out.println(" "+tcode[4]+"\t"+tname[4]+"\t\t10:10 P.M"+"\t"+seat[4]+"\t"+price[4]);
}
catch(Exception e)
{
System.err.println("\nERROR IS :" + e);
SUBJECT : Programming Skills – IV (Java)
(.. 1 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
}
}
}
class booking extends info
{
int no;
String name;
int ticket,i,k,t_price,pay,j=1,cust;
int code;
public void book()
{
cust=j;
j++;
try
{
DataInputStream s=new DataInputStream(System.in);
System.out.println("WHICH TRAIN YOU WANT TO RESERVE :-");
code=Integer.parseInt(s.readLine());
if(code==tcode[i])
{
System.out.println("------------------------------");
System.out.println("ENTER THE YOUR NAME : ");
Scanner sc = new Scanner(System.in);
name = sc.next();
System.out.println("------------------------------");
System.out.println("HOW MANY TICKET YOU WANT TO BOOK : ");
ticket = sc.nextInt();
System.out.println("------------------------------");
System.out.println();
}
else
{
JOptionPane.showMessageDialog(null,"ENTER VALID TRAIN CODE...!");
System.exit(0);
}
for(int i=0;i<3;i++)
{
if(code==tcode[i])
{
t_price=price[i];
break;
}
}
pay=t_price*ticket;
for(int i=0;i<3;i++)
{
if(code==tcode[i])
{
seat[i]-=ticket;
break;
}
}
}
catch(Exception e)
{
System.err.println("\nERROR IS :" + e);
}
}
public void cancle()
SUBJECT : Programming Skills – IV (Java)
(.. 2 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
try
{
DataInputStream dis=new DataInputStream(System.in);
int ccode,j;
System.out.println("ENTER THE CODE OF CUSTOMER : ");
ccode=Integer.parseInt(dis.readLine());
if(cust==ccode)
{
for(i=0;i<4;i++)
{
if( code == tcode[i])
{
seat[i]+=ticket;
}
}
JOptionPane.showMessageDialog(null,"CANCLE SUCESSFULLY...!");
}
}
catch(Exception e)
{
System.err.println("\nERROR IS :" + e);
}
}
public void display()
{
System.out.println("CUST_NO\tNAME\tTRAIN NAME\t\tNO OF TICKET\tPAYMENT");
System.out.println("-------------------------------------------------------------------------------");
System.out.println(cust+"\t"+name+"\t"+tname[k]+"\t\t"+ticket+"\t\t"+pay);
JOptionPane.showMessageDialog(null,name+" YOUR SEAT RESERVED...!");
}
}
class prog_1 extends booking
{
public static void main(String []args) throws IOException
{
int ch;
booking B=new booking();
DataInputStream ip = new DataInputStream(System.in);
try
{
JOptionPane.showMessageDialog(null, "WELCOME TO RAILWAY RESERVATION SYSTEM...!");
do
{
System.out.println();
System.out.println("------------------------------");
System.out.println("\n[1].TRAIN INFORMATION");
System.out.println("\n[2].BOOKING");
System.out.println("\n[3].CANCLE BOOKING");
System.out.println("\n[4].EXIT");
System.out.println("------------------------------");
System.out.println("ENTER YOUR CHOICE :");
ch = Integer.parseInt(ip.readLine());
System.out.println("------------------------------");
switch(ch)
{
case 1: B.put_info();
break;
SUBJECT : Programming Skills – IV (Java)
(.. 3 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
case 2: B.book();
B.display();
break;
case 3: B.cancle();
B.put_info();
break;
case 4: System.exit(0);
}
}while(ch<=4);
}
catch (Exception e)
{
System.err.println("ERROR : " + e);
}
}
}
(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 .
import java.io.*;
public class prg2
{
public static void main(String[] arg) throws Exception
{
if(arg.length!=0)
{
try
{
int LastNo=Integer.parseInt(arg[0]);
int Space=LastNo;
for(int i=1;i<=LastNo;i++)
{
for(int k=Space;k>=1;k--)
System.out.print(" ");
for(int j=1;j<=i;j++)
{
System.out.print(" * ");
}
Space--;
System.out.println();
}
}
catch(Exception ex)
{
System.out.println("ERROR : "+ex);
}
}
else
{
System.out.println("ENTER THE ARGUMENT");
}
}
}
(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
SUBJECT : Programming Skills – IV (Java)
(.. 4 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
3: Third Student Name is =Harry
Hint: An array may be used for converting from numeric values from 1 to 20 into String.
import java.io.*;
class pro_3
{
public static void main(String []args) throws IOException
{
try
{
int i;
String str[] = new String[15];
String name[] = new String[15];
str[0] ="FIRST";
str[1]= "SECOND";
str[2] ="THIRD";
str[3] ="FOUR";
str[4]= "FIVE";
str[5] ="SIX";
str[6] ="SEVEN";
str[7]= "EIGHT";
str[8] ="NINE";
str[9] ="TEN";
str[10]= "ELEVAN";
str[11] ="TWELVE";
str[12] ="THARTINNE";
str[13]= "FOURTINNE";
str[14] ="FIFTINNE";
int len=args.length;
for (i = 0; i < len ; i++)
{
name[i]=args[i];
}
System.out.println("\n------------------------------------------");
System.out.println("\tNUMBER OF ARGUMENTS=" + args.length);
System.out.println("------------------------------------------");
for (i = 0; i < len ; i++)
{
int j=i+1;
System.out.println("\n " + j + ": \t" + str[i] + " \tSTUDENT IS =\t" + name[i]);
}
}
catch (Exception e)
{
System.err.println("ERROR IS :" + e);
}
}
}
(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 of assigning a high integer value (8 digits and above) to a float and
casting it back to int and printing.
import java.io.*;
import java.util.Scanner;
class prog_4
{
public static void main(String []args) throws IOException
{
try
{
DataInputStream dis=new DataInputStream(System.in);
SUBJECT : Programming Skills – IV (Java)
(.. 5 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
Scanner sc = new Scanner(System.in);
System.out.println("\nENTER INTEGER NUMBER :");
int number=Integer.parseInt(dis.readLine());
double num=number;
System.out.println("\nAFTER CASTING INTEGER INTO FLOAT :"+num);
number=(int)num;
System.out.println("\nAFTER CASTING FLOAT INTO INTEGER :"+number);
float result=number/0;
System.out.println();
System.out.println("AFTER DIVIDING BY ZERO THE VALUE IS :"+result);
System.out.println();
}
catch (Exception e)
{
System.out.println();
System.err.println("ERROR IS:"+e);
}
}
}
(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 temperatures for the four weeks.
import java.util.*;
class state
{
public static void average(double arr[])
{
Scanner c=new Scanner(System.in);
double sum=0;
for(int i=0;i<2;i++)
{
sum=sum+arr[i];
}
System.out.println(sum/2);
}
}
class prog_5
{
public static void main(String []args)
{
double ch[]=new double[2];
state s=new state();
double mon[][]=new double[2][2];
Scanner sc=new Scanner(System.in);
for(int i=0;i<2;i++)
{
int k=i+1;
System.out.println("\nENTER THE VALUE OF WEEK "+ k +":");
for(int j=0;j<2;j++)
{
int a=j+1;
System.out.println("\nENTER THE VALUE OF "+ a +":");
mon[i][j]=sc.nextInt();
ch[i]=ch[i]+mon[i][j];
}
}
s.average(ch);
SUBJECT : Programming Skills – IV (Java)
(.. 6 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
}
}
(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 Test Product, with the main method to test the
methods and constructors of the Product class.
class product
{
int pcode;
String pname,mname;
product(int pcode,String pname,String mname)
{
this.pcode=pcode;
this.pname=pname;
this.mname=mname;
}
void display()
{
System.out.println("PRODUCT CODE : "+pcode);
System.out.println("PROFUCT NAME : "+pname);
System.out.println(“MANUFACTURE NAME : "+mname);
//System.out.println(this);
}
}
public class prog_6
{
public static void main(String[] a)
{
product p1,p2;
p1=new product(001,"computer","HCL");
p2=new product(002,"AC","Godrej");
p1.display();
p2.display();
}
}
(7). Define a class called Cartesian Point, which has two instance variables, x and y. Provide the methods get X() and
get Y() 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 the same values, . Provide constructors with two parameters and overload to work with one parameter as
well. Now define a class called Test Cartesian Point, with the main method to test the various methods in the
Cartesian Point class.
import java.util.*;
class Cartesian_Point
{
int x,y;
Cartesian_Point(int p,int q)
{
x=p;
y=q;
}
int get_x()
{
return x;
}
int get_y()
{
return y;
}
SUBJECT : Programming Skills – IV (Java)
(.. 7 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
void move(int p,int q)
{
int tmp;
x=p;
y=q;
tmp=x;
x=y;
y=tmp;
}
void move(int p)
{
x=y=p;
}
void display()
{
System.out.println("-------------------------------------");
System.out.println("THE VALUE OF X IS:" +x);
System.out.println("THE VALUE OF Y IS:" +y);
}
}
class prog_7
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
Cartesian_Point c;
System.out.println("ENETR THE VALUE OF X :" );
int x=sc.nextInt();
System.out.println("ENETR THE VALUE OF Y :");
int y=sc.nextInt();
c=new Cartesian_Point(x,y);
c.move(c.get_x(),c.get_y());
c.display();
c.move(c.get_x());
c.display();
}
}
(8). Define a class called Triangle, which has constructor with three parameters, which are of type Cartesian Point,
defined in the exercise 7. Provide methods to find the area and the perimeter of the Triangle, a method display() to
display the three Cartesian Points separated by ':' character, a method move() to move the first Cartesian Point 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 Cartesian Point and other is the angle in clockwise direction. Overload
the move method to work with Cartesian Point as a parameter. Now define a class called Test Triangle to test the
various methods defined in the Triangle class. Similarly also define a class called Rectangle which has four Cartesian
Point.
class CartesianPoint
{
public int x,y;
public void getx(int a)
{
x=a;
}
public void gety(int a)
{
y=a;
}
public void move(int a, int b)
{
x=a;
SUBJECT : Programming Skills – IV (Java)
(.. 8 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
y=b;
}
public void move(int a)
{
x=a;
y=a;
}
}
class Triangle
{
public Triangle(CartesianPoint a, CartesianPoint b, CartesianPoint c)
{
a.getx(20);
a.gety(10);
b.gety(22);
b.gety(30);
c.getx(40);
c.gety(50);
}
public float area(float b, float h)
{
return (0.5f*b*h);
}
public float parimeter(float a, float b, float c)
{
return (a+b+c);
}
public void display(CartesianPoint a, CartesianPoint b, CartesianPoint c)
{
System.out.println("A) " + a.x + ":" + a.y);
System.out.println("B) " + b.x + ":" + b.y);
System.out.println("C) " + c.x + ":" + c.y);
}
public void moveTri(CartesianPoint a, CartesianPoint b, CartesianPoint c,int ax, int ay, int bx, int by, int cx, int cy)
{
a.move(ax, ay);
b.move(bx, by);
c.move(cx, cy);
}
public void moveTri(CartesianPoint a, CartesianPoint b, CartesianPoint c, int ax, int bx, int cx)
{
a.move(ax);
b.move(bx);
c.move(cx);
}
public void rotate(CartesianPoint a, CartesianPoint b, CartesianPoint c, int r)
{
int xr=50;
int yr=50;
int xa=a.x;
int ya=a.y;
a.x=(int) ((int) xr + ((xa - xr) * Math.cos((r * 3.14) / 180)) - ((ya - yr) * Math.sin((r * 3.14) / 180)));
a.y=(int) ((int) yr + ((xa - xr) * Math.sin((r * 3.14) / 180)) - ((ya - yr) * Math.cos((r * 3.14) / 180)));
xr=50;
yr=50;
xa=b.x;
ya=b.y;
b.x=(int) ((int) xr + ((xa - xr) * Math.cos((r * 3.14) / 180)) - ((ya - yr) * Math.sin((r * 3.14) / 180)));
SUBJECT : Programming Skills – IV (Java)
(.. 9 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
b.y=(int) ((int) yr + ((xa - xr) * Math.sin((r * 3.14) / 180)) - ((ya - yr) * Math.cos((r * 3.14) / 180)));
xr=50;
yr=50;
xa=c.x;
ya=c.y;
c.x=(int) ((int) xr + ((xa - xr) * Math.cos((r * 3.14) / 180)) - ((ya - yr) * Math.sin((r * 3.14) / 180)));
c.y=(int) (yr + ((xa - xr) * Math.sin((r * 3.14) / 180)) - ((ya - yr) * Math.cos((r * 3.14) / 180)));
}
}
class Rectangle
{
public Rectangle(CartesianPoint a, CartesianPoint b, CartesianPoint
c, CartesianPoint d)
{
a.getx(10);
a.gety(25);
b.getx(24);
b.gety(42);
c.getx(32);
c.gety(21);
d.getx(25);
d.gety(21);
}
public void display(CartesianPoint a, CartesianPoint b, CartesianPoint c, CartesianPoint d)
{
System.out.println("A) " + a.x + ":" + a.y);
System.out.println("B) " + b.x + ":" + b.y);
System.out.println("C) " + c.x + ":" + c.y);
System.out.println("D) " + d.x + ":" + d.y);
}
}
public class prog_8
{
public static void main(String [] args)
{
//Use For Triangle Class
CartesianPoint a = new CartesianPoint();
CartesianPoint b = new CartesianPoint();
CartesianPoint c = new CartesianPoint();
//Use For Rectangle Class
CartesianPoint d = new CartesianPoint();
Triangle Tri_obj = new Triangle(a, b, c);
System.out.println("********************************");
System.out.println("First CartesianPoint init for Triangle");
System.out.println("********************************");
Tri_obj.display(a, b, c);
float area_count = Tri_obj.area(15.5f, 10f);
System.out.println("********************************");
System.out.println("the Area of the Triangle: " +area_count);
System.out.println("********************************");
float tri_parimeter = Tri_obj.parimeter(21f, 12f, 8f);
System.out.println("********************************");
System.out.println("The Perimeter of the Triangle: " +tri_parimeter);
System.out.println("********************************");
Tri_obj.moveTri(a, b, c, 25, 33, 20, 10, 35, 42);
SUBJECT : Programming Skills – IV (Java)
(.. 10 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
System.out.println("********************************");
System.out.println("After Move CartesianPoint");
System.out.println("********************************");
Tri_obj.display(a, b, c);
Tri_obj.rotate(a, b, c, 50);
System.out.println("********************************");
System.out.println("After Rotate CartesianPoint");
System.out.println("********************************");
Tri_obj.display(a, b, c);
Rectangle rect_obj = new Rectangle(a, b, c, d);
System.out.println("********************************");
System.out.println("First CartesianPoint init for Rectangle");
System.out.println("********************************");
rect_obj.display(a, b, c, d);
}
}
(9). Override the to String, equals and the hash Code 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 to String method.
class Cartesianpoint
{
int x,y;
Cartesianpoint(int x,int y)
{
this.x=x;
this.y=y;
}
}
public class prog_9
{
Cartesianpoint a,b,c;
prog_9(Cartesianpoint a,Cartesianpoint b,Cartesianpoint c)
{
this.a=a;
this.b=b;
this.c=c;
}
void display()
{
System.out.print(toString());
}
public String toString()
{
return("For This Instance A(x,y) is ("+a.x+","+a.y+")\n For point B(x,y) is ("+b.x+","+b.y+")\n
For point C(x,y) is ("+c.x+","+c.y+")\n\n");
}
public boolean equals(prog_9 obj)
{
if(this.a.x==obj.a.x && this.a.y==obj.a.y)
{
if(this.b.x==obj.b.x && this.b.y==obj.b.y)
{
if(this.c.x==obj.c.x && this.c.y==obj.c.y)
{
return(true);
}
}
SUBJECT : Programming Skills – IV (Java)
(.. 11 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
}
return(false);
}
public int hashCode()
{
int i=Integer.parseInt(""+a.x+""+a.y+""+""+b.x+""+b.y+""+""+c.x+""+c.y+"");
return(i);
}
public static void main(String[] arg)
{
Cartesianpoint a,b,c;
a=new Cartesianpoint(1,1);
b=new Cartesianpoint(3,5);
c=new Cartesianpoint(5,1);
prog_9 p,q;
p=new prog_9(a,b,c);
a=new Cartesianpoint(1,1);
b=new Cartesianpoint(3,5);
c=new Cartesianpoint(5,1);
q=new prog_9(a,b,c);
p.display();
q.display();
System.out.print(p.equals(q));
System.out.println(p.hashCode());
System.out.println(q.hashCode());
}
}
(10). Define an abstract class called Polygon. Provide a constructor which takes an array of Cartesian Point 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 Polygon, and overload to make it work for Cartesian Point 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 CartesianPoint
{
int x,y;
public void getx(int a)
{
x=a;
}
public void gety(int a)
{
y=a;
}
public void move(int a, int b)
{
x=a;
y=b;
}
public void move(int a)
{
x=a;
y=a;
}
}
abstract class Rectangle extends CartesianPoint
{
public Rectangle(){}
public Rectangle(CartesianPoint[] a)
SUBJECT : Programming Skills – IV (Java)
(.. 12 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
a[0].getx(10);
a[0].gety(25);
a[1].getx(24);
a[1].gety(42);
a[2].getx(32);
a[2].gety(42);
a[3].getx(25);
a[3].gety(21);
}
public void display(CartesianPoint a, CartesianPoint b, CartesianPoint c, CartesianPoint d)
{
System.out.println("A) " + a.x + ":" + a.y);
System.out.println("B) " + b.x + ":" + b.y);
System.out.println("C) " + c.x + ":" + c.y);
System.out.println("D) " + d.x + ":" + d.y);
}
public int area(int a, int b)
{
return a*b;
}
}
abstract class Triangle extends Rectangle
{
public Triangle(){}
public Triangle(CartesianPoint [] a)
{
a[0].getx(20);
a[0].gety(10);
a[1].getx(22);
a[1].gety(30);
a[2].getx(40);
a[2].gety(50);
}
public float Area(float b, float h)
{
return (0.5f*b*h);
}
public float parimeter(float a, float b, float c)
{
return (a+b+c);
}
public void display(CartesianPoint a, CartesianPoint b, CartesianPoint c)
{
System.out.println("A) " + a.x + ":" + a.y);
System.out.println("B) " + b.x + ":" + b.y);
System.out.println("C) " + c.x + ":" + c.y);
}
public void moveTri(CartesianPoint a, CartesianPoint b, CartesianPoint c, int ax, int ay, int bx, int by, int cx, int cy)
{
a.move(ax, ay);
a.move(bx, by);
a.move(cx, cy);
}
public void moveTri(CartesianPoint a, CartesianPoint b, CartesianPoint c, int ax, int bx, int cx)
{
a.move(ax);
b.move(bx);
c.move(cx);
}
SUBJECT : Programming Skills – IV (Java)
(.. 13 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
public void rotate(CartesianPoint a, CartesianPoint b, CartesianPoint c, int r)
{
int xr=50;
int yr=50;
int xa=a.x;
int ya=a.y;
a.x=(int) ((int) xr + ((xa - xr) * Math.cos((r * 3.14) / 180)) - ((ya - yr) * Math.sin((r * 3.14) / 180)));
a.y=(int) ((int) yr + ((xa - xr) * Math.sin((r * 3.14) / 180)) - ((ya - yr) * Math.cos((r * 3.14) / 180)));
xr=50;
yr=50;
xa=b.x;
ya=b.y;
b.x=(int) ((int) xr + ((xa - xr) * Math.cos((r * 3.14) /180)) - ((ya - yr) * Math.sin((r * 3.14) / 180)));
b.y=(int) ((int) yr + ((xa - xr) * Math.sin((r * 3.14) /180)) - ((ya - yr) * Math.cos((r * 3.14) / 180)));
xr=50;
yr=50;
xa=c.x;
ya=c.y;
c.x=(int) ((int) xr + ((xa - xr) * Math.cos((r * 3.14) /180)) - ((ya - yr) * Math.sin((r * 3.14) / 180)));
c.y=(int) (yr + ((xa - xr) * Math.sin((r * 3.14) / 180)) -((ya - yr) * Math.cos((r * 3.14) / 180)));
}
}
abstract class Polygon extends Triangle
{
int len;
public Polygon(){}
public Polygon(CartesianPoint[] a)
{
a[0].getx(10);
a[0].gety(50);
a[1].getx(20);
a[1].gety(30);
a[2].getx(35);
a[2].gety(10);
a[3].getx(20);
a[3].gety(50);
len=a.length;
}
public int perimeter(int n)
{
return n*len;
}
abstract float area(float b, float h);
public void move(int x, int y, int pos, CartesianPoint[] a)
{
a[pos].getx(x);
a[pos].gety(y);
}
}
//implementation of area method
class TestPolygon extends Polygon
{
float area(float b, float h)
{
return (b*h);
}
}
SUBJECT : Programming Skills – IV (Java)
(.. 14 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
public class prog_10
{
public static void main(String [] arg)
{
TestPolygon t1 = new TestPolygon();
//polygon
float a = t1.area(12f, 23f);
System.out.println(""+a);
//triangle
float b = t1.Area(25f, 35f);
System.out.println(""+b);
//rectangle
int c = t1.area(23,5);
System.out.println(""+c);
}
}
(11). Make the class Cartesian Point, 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 Test Cartesian Point, Test Triangle, Test
Rectangle and Test Polygon 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 P11.edu.gtu.geometry;
public class Cartesianpoint
{
public int x,y;
public Cartesianpoint(int x)
{
this(x,x);
}
public Cartesianpoint(int x,int y)
{
this.x=x;
this.y=y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move(int x)
{
move(x,x);
}
public void move(int x,int y)
{
this.x=x;
this.y=y;
}
public void display()
{
System.out.println("X : "+x+"\nY : "+y);
}
}
[ SHAPE DIRECTORY ]
package P11.edu.gtu.geometry.shapes;
SUBJECT : Programming Skills – IV (Java)
(.. 15 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
import P11.edu.gtu.geometry.Cartesianpoint;
public abstract class polygon
{
Cartesianpoint point[];
int noofp;
polygon(Cartesianpoint point[])
{
this.point=point;
noofp=point.length;
}
public double perimeter()
{
double pari=0;
for(int i=0;i<noofp;i++)
{
if(i==noofp-1)
{
pari+=Math.sqrt((point[i].x-point[0].x)*(point[i].x-point[0].x)+(point[i].ypoint[0].y)*(point[i].y-point[0].y));
}
else
{
pari+=Math.sqrt((point[i].x-point[i+1].x)*(point[i].x-point[i+1].x)+(point[i].ypoint[i+1].y)*(point[i].y-point[i+1].y));
}
}
return(pari);
}
public void move(int X,int Y)
{
int tempx=X-point[0].x;
int tempy=Y-point[0].y;
point[0].x=X;
point[0].y=Y;
for(int i=1;i<noofp;i++)
{
point[i].x += tempx;
point[i].y += tempy;
}
}
abstract void area();
}
class Rectangle extends polygon
{
Cartesianpoint a,b,c,d;
Cartesianpoint points[]=new Cartesianpoint[4];
double ab,bc,cd,da;
Rectangle(Cartesianpoint a,Cartesianpoint b,Cartesianpoint c,Cartesianpoint d)
{
super(new Cartesianpoint[] {a,b,c,d});
this.a=a;
this.b=b;
this.c=c;
this.d=d;
ab=Math.sqrt((b.x-a.x)*(b.x-a.x) + (b.y-a.y)*(b.y-a.y));
bc=Math.sqrt((c.x-b.x)*(c.x-b.x) + (c.y-b.y)*(c.y-b.y));
cd=Math.sqrt((d.x-c.x)*(d.x-c.x) + (d.y-c.y)*(d.y-c.y));
da=Math.sqrt((a.x-d.x)*(a.x-d.x) + (a.y-d.y)*(a.y-d.y));
}
void display()
SUBJECT : Programming Skills – IV (Java)
(.. 16 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
System.out.println("Point A = ("+a.x+" , "+a.y+")");
System.out.println("Point B = ("+b.x+" , "+b.y+")");
System.out.println("Point C = ("+c.x+" , "+c.y+")");
System.out.println("Point C = ("+d.x+" , "+d.y+")");
}
void area()
{
System.out.println("Area of Rectangle is : "+ab*bc*2);
}
}
package P11.edu.gtu.geometry.shapes;
import P11.edu.gtu.geometry.Cartesianpoint;
public class Triangle extends polygon
{
Cartesianpoint a,b,c;
double ab,bc,ca,height,x,y;
public Triangle(Cartesianpoint a,Cartesianpoint b,Cartesianpoint c)
{
super(new Cartesianpoint[] {a,b,c});
this.a=a;
this.b=b;
this.c=c;
ab=Math.sqrt((b.x-a.x)*(b.x-a.x) + (b.y-a.y)*(b.y-a.y));
bc=Math.sqrt((c.x-b.x)*(c.x-b.x) + (c.y-b.y)*(c.y-b.y));
ca=Math.sqrt((a.x-c.x)*(a.x-c.x) + (a.y-c.y)*(a.y-c.y));
x=(b.x+c.x)/2;
y=(b.y+c.y)/2;
height=Math.sqrt((x-a.x)*(x-a.x) + (y-a.y)*(y-a.y));
}
public void display()
{
System.out.println("Point A = ("+a.x+" , "+a.y+")");
System.out.println("Point B = ("+b.x+" , "+b.y+")");
System.out.println("Point C = ("+c.x+" , "+c.y+")");
}
public void area()
{
System.out.println("Area of Triangle is : "+(bc*height)/2);
}
}
[ TEST DIRECTORY ]
public class TestPolygon
{
public static void main(String[] args)
{
System.out.println("\n :FOR TRIANGLE: \n");
Cartesianpoint a,b,c,d;
a=new Cartesianpoint(5,5);
b=new Cartesianpoint(2,3);
c=new Cartesianpoint(7,3);
Triangle t=new Triangle(a,b,c);
t.display();
t.move(7,7);
System.out.println("\nAfter Move \n");
t.display();
t.area();
SUBJECT : Programming Skills – IV (Java)
(.. 17 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
System.out.println(t.perimeter());
System.out.println("\n********************************\n");
System.out.println(" :FOR RECTANGLE: \n");
a=new Cartesianpoint(1,1);
b=new Cartesianpoint(1,3);
c=new Cartesianpoint(6,3);
d=new Cartesianpoint(1,6);
Rectangle r=new Rectangle(a,b,c,d);
r.display();
r.move(2,2);
System.out.println("\nAfter Move \n");
r.display();
r.area();
System.out.println(r.perimeter());
}
}
package P11.edu.gtu.test;
import P11.edu.gtu.geometry.shapes.*;
import P11.edu.gtu.geometry.*;
public class TestTriangle
{
public static void main(String[] args)
{
System.out.println("\n :FOR TRIANGLE: \n");
Cartesianpoint a,b,c,d;
a=new Cartesianpoint(5,5);
b=new Cartesianpoint(2,3);
c=new Cartesianpoint(7,3);
Triangle t=new Triangle(a,b,c);
t.display();
t.move(7,7);
System.out.println("\nAfter Move \n");
t.display();
t.area();
System.out.println(t.perimeter());
System.out.println("\n********************************\n");
}
}
(12). Update the classes Triangle and Rectangle, to throw an exception if the Cartesian Point instances passed as
parameter does not specify an appropriate Triangle or Rectangle. e.g. 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.
[dmeoPackage\edu\gtu\geometry]
package edu.gtu.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);
}
SUBJECT : Programming Skills – IV (Java)
(.. 18 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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);
}
}
package edu.gtu.geometry;
public abstract class Polygon
{
public Cartesian_Point[] x;
int n;
public Polygon(Cartesian_Point[] x)
{
int i=0;
for(Cartesian_Point y : x)
{
i++;
}
n = i-1;
this.x = new Cartesian_Point[i];
for(int j=0;j<n;j++)
{
this.x[j] = x[j];
}
}
public int parameter()
{
return n;
}
public abstract double area();
public String toString()
{
String s = "[";
for(int i=0;i<n;i++)
{
s = s.concat(""+x[i]);
}
s=s.concat("]");
return s;
}
}
package edu.gtu.geometry;
SUBJECT : Programming Skills – IV (Java)
(.. 19 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
public class Rectangle extends Polygon
{
public Rectangle(Cartesian_Point p[])throws DemoException
{
super(p);
if(parameter()!=4)
throw new DemoException("Argumet are [" + parameter() + "]");
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);
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
throw new DemoException("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);
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)
SUBJECT : Programming Skills – IV (Java)
(.. 20 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
{
//
:: MCA – III ::
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)
{
}
}
package edu.gtu.geometry;
public class Triangle extends Polygon
{
public Triangle(Cartesian_Point p1[])throws DemoException
{
super(p1);
if(parameter()!=3)
throw new DemoException("Argumet are [" + parameter() + "]");
}
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)
{
}
}
package edu.gtu.geometry;
public class DemoException extends Exception
{
SUBJECT : Programming Skills – IV (Java)
(.. 21 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
public DemoException(String msg)
{
super(msg);
}
public String toString()
{
return super.toString();
}
}
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");
}
}
(13). Define a class called Polygon Manager, which manages a number of Polygon instances. Provide methods to add,
remove and list the Polygon instances managed by it. Test the methods of Polygon Manager 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
{
SUBJECT : Programming Skills – IV (Java)
(.. 22 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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)+"=->");
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)
{
SUBJECT : Programming Skills – IV (Java)
(.. 23 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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++)
{
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
{
SUBJECT : Programming Skills – IV (Java)
(.. 24 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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
{
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++;
SUBJECT : Programming Skills – IV (Java)
(.. 25 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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++)
{
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
SUBJECT : Programming Skills – IV (Java)
(.. 26 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
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 =->");
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................");
}
SUBJECT : Programming Skills – IV (Java)
(.. 27 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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...........");
System.out.println("Enter Your Choice =->");
}
}
(14). Define a class called Statistical Data which manages a number of readings of type int. Provide a method to set
Data 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
4. variance
5. standard deviation
6. specified percentile (between 0 – 100) the method should have a parameter.
7. specified quartile (between 1 - 3) the method should have a parameter.
8. interquartile range
Use this class to calculate the given statistics for the data regarding the total of marks obtained by all the students in
your class in the previous exams. The data may be accepted one by one for each student from the keyboard.
[MYPACK]
package MyPack;
import java.util.Scanner;
import java.lang.Math;
import java.util.Arrays;
public class StatisticalData
{
private int arr[];
public Scanner S;
public StatisticalData()
{
S = new Scanner(System.in);
}
public void setData(int n)
SUBJECT : Programming Skills – IV (Java)
(.. 28 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
arr = new int[n];
}
public void addData()
{
for(int i=0;i<arr.length;i++)
{
System.out.print("Enter Data for ["+i+"] : ");
arr[i]=S.nextInt();
}
}
public void resetData()
{
Arrays.fill(arr,0);
}
public float getMean()
{
int Ex=0;
for(int i=0;i<arr.length;i++)
Ex+=arr[i];
return Ex/arr.length;
}
public int getMedian()
{
int temp[];
temp=arr.clone();
Arrays.sort(temp);
if(temp.length % 2 == 0)
{
int a = temp.length/2;
return temp[a]+temp[a+1]/2;
}
else
{
int a = (int) temp.length/2;
return temp[a];
}
}
public int getMode()
{
int [] temp;
temp = arr.clone();
Arrays.sort(temp);
return temp[temp.length-1];
}
public int getPercentile(int p)
{
int [] temp;
temp = arr.clone();
Arrays.sort(temp);
float i = (p/100)*arr.length;
return temp[(int) i];
}
public int getQuartile(int p)
{
float i;
int [] temp;
temp = arr.clone();
Arrays.sort(temp);
switch(p)
SUBJECT : Programming Skills – IV (Java)
(.. 29 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
case 1 : i = (25/100)*arr.length;
break;
case 2 : i = (50/100)*arr.length;
break;
case 3 : i = (75/100)*arr.length;
break;
default :
System.out.println("Invalid quartile");
return 0;
}
return temp[(int) i];
}
public int getIQR()
{
return getQuartile(3)-getQuartile(1);
}
public float getVariance()
{
float x_xi,x_xi2,Ex_xi2=0;
for(int i =0;i<arr.length;i++)
{
x_xi=arr[i]-getMean();
x_xi2=x_xi*x_xi;
Ex_xi2+=x_xi2;
}
return Ex_xi2/arr.length-1;
}
public float getSD()
{
return (float) Math.sqrt(getVariance());
}
}
import MyPack.StatisticalData;
class prog_14
{
public static void main(String args[])
{
StatisticalData Ex = new StatisticalData();
int n;
System.out.print("Enter N : ");
n=Ex.S.nextInt();
Ex.setData(n);
while(true)
{
System.out.println("-------------------------------------");
System.out.println("1. Add Data");
System.out.println("2. Reset Data");
System.out.println("3. Get Mean");
System.out.println("4. Get Median");
System.out.println("5. Get Mode ");
System.out.println("6. Get Variancel ");
System.out.println("7. Get Standard Deviation");
System.out.println("8. Get Specified Percentile");
System.out.println("9. Get Specified Quartile");
System.out.println("10 Get Interquartile Range");
System.out.println("11. Exit ");
System.out.print("Enter your choice...");
n=Ex.S.nextInt();
SUBJECT : Programming Skills – IV (Java)
(.. 30 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
switch(n)
{
case 1 : Ex.addData();
break;
case 2 : Ex.resetData();
break;
case 3 : System.out.println("The mean is "+Ex.getMean());
break;
case 4 : System.out.println("The median is "+Ex.getMedian());
break;
case 5 : System.out.println("The Mode is "+Ex.getMode());
break;
case 6 : System.out.println("The Variance is "+Ex.getVariance());
break;
case 7 : System.out.println("The Standard Deviation is "+Ex.getSD());
break;
case 8 :
{
int p;
System.out.print("Enter P : ");
p=Ex.S.nextInt();
if (p >= 1 && p <=100)
Ex.getPercentile(p);
else
System.out.println("Invalid percentile");
break;
}
case 9 :
{
int p;
System.out.println("Enter specific Quartile (1|2|3)");
p=Ex.S.nextInt();
System.out.println("The Specific Quartile is "+Ex.getQuartile(p));
break;
}
case 10 : System.out.println("The IQR is"+Ex.getIQR());
break;
case 11 : System.exit(1);
default : System.out.println("Invalid Input...");
}
}
}
}
Program : 24 Create a class called Statistical Data, which has capability of maintaining data regarding multiple
ariables. It should have a method to specify the variable names as String array and the method to oad 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 lass 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;
class StatisticalData
SUBJECT : Programming Skills – IV (Java)
(.. 31 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
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());
SUBJECT : Programming Skills – IV (Java)
(.. 32 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
}
}
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);
SUBJECT : Programming Skills – IV (Java)
(.. 33 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
}
sab=tatb/4;
sa=ta2/5;
sb=tb2/5;
sa=Math.sqrt(sa);
sb=Math.sqrt(sb);
cor_coef=sab/sa*sb;
System.out.println("correlation co-efficient: " + cor_coef);
}
}
class Prog_24
{
public static void main(String args[])
{
StatisticalData x=new StatisticalData();
x.get();
x.correl_coeff();
}
}
Program : 15
Update the class Statistical Data, and define a method called load From CSV, which takes as parameter an Input
Stream, 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...");
SUBJECT : Programming Skills – IV (Java)
(.. 34 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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++;
}
String.....
}
catch(NumberFormatException nfe) {
System.out.println("Marks can't be the
OR can not leave it blank.....");
add();
}
}
}
float mean() {
display();
float sum=0;
for(int i=0;i<n;i++){
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];
SUBJECT : Programming Skills – IV (Java)
(.. 35 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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) {
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{
SUBJECT : Programming Skills – IV (Java)
(.. 36 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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++;
}
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....");
}
SUBJECT : Programming Skills – IV (Java)
(.. 37 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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;
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;
}
SUBJECT : Programming Skills – IV (Java)
(.. 38 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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;
while(flag==0) {
try{
System.out.print("Enter value for Specified Percentile (0-100) :");
int
p=Integer.parseInt(br.readLine());
if( p > 100 ||
p < 1 ) {
System.out.println("Enter between 1 - 100 .....");
}
SUBJECT : Programming Skills – IV (Java)
(.. 39 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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 (1-3) :");
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....");
}
}
SUBJECT : Programming Skills – IV (Java)
(.. 40 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
catch(FileNotFoundException e)
{
System.out.println("System can't find your inputed
path....");
}
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, re-enter your selection....");
break;
}
}
}
}
}
SUBJECT : Programming Skills – IV (Java)
(.. 41 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
Program16:
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();
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()
SUBJECT : Programming Skills – IV (Java)
(.. 42 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
{
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_
marks[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()];
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());
SUBJECT : Programming Skills – IV (Java)
(.. 43 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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());
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());
}
}
Program17:
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.*;
SUBJECT : Programming Skills – IV (Java)
(.. 44 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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)
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
{
SUBJECT : Programming Skills – IV (Java)
(.. 45 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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_marks[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");
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]);
SUBJECT : Programming Skills – IV (Java)
(.. 46 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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());
}
}
Program 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….
import java.awt.*;
import java.awt.event.*;
import java.util.*; import javax.swing.*;
import javax.swing.text.*;
public class AutoComplete extends JComboBox implements JComboBox.KeySelectionManager
{
private String searchFor;
private long lap;
public class CBDocument extends PlainDocument
{
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException
{
if (str==null) return; super.insertString(offset, str, a);
if(!isPopupVisible() && str.length() != 0) fireActionEvent();
}}
public AutoComplete(Object[] items)
{
super(items);
lap = new java.util.Date().getTime(); setKeySelectionManager(this);
JTextField tf;
if(getEditor() != null)
{
tf = (JTextField)getEditor().getEditorComponent();
if(tf != null)
{
tf.setDocument(new CBDocument());
addActionListener(new ActionListener()
{
SUBJECT : Programming Skills – IV (Java)
(.. 47 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
public void actionPerformed(ActionEvent evt)
{
JTextField tf = (JTextField)getEditor().getEditorComponent();
String text = tf.getText();
ComboBoxModel aModel = getModel();
String current; for(int i = 0; i < aModel.getSize(); i++)
{
current = aModel.getElementAt(i).toString();
if(current.toLowerCase().startsWith(text.toLowerCase()))
{
tf.setText(current);
tf.setSelectionStart(text.length());
tf.setSelectionEnd(current.length());
break; } } } });
}}}
public int selectionForKey(char aKey, ComboBoxModel aModel)
{
long now = new java.util.Date().getTime();
if (searchFor!=null && aKey==KeyEvent.VK_BACK_SPACE && searchFor.length()>0)
{
searchFor = searchFor.substring(0, searchFor.length() -1);
}
else { if(lap + 1000 < now) searchFor = "" + aKey; else searchFor = searchFor + aKey;
}
lap = now; String current;
for(int i = 0; i < aModel.getSize(); i++)
{
current = aModel.getElementAt(i).toString().toLowerCase();
if (current.toLowerCase().startsWith(searchFor.toLowerCase())) return i;
}
return -1;
}
public void fireActionEvent()
{
super.fireActionEvent();
}
public static void main(String arg[])
{
JFrame f = new JFrame("AutoCompleteComboBox");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200,300);
Container cp= f.getContentPane();
cp.setLayout(null);
String[] names= {"Beate", "Claudia", "Fjodor", "Fred", "Friedrich","Fritz", "Frodo", "Hermann", "Willi"};
JComboBox cBox= new AutoComplete(names);
Locale[] locales = Locale.getAvailableLocales();
JComboBox cBox= new AutoComplete(names);
cBox.setBounds(50,50,100,21);
cBox.setEditable(true);
cp.add(cBox); f.setVisible(true);
}}
Program : 19
Create an applet which has a Text Field to accept a URL string, and displays the document of the URL string in a new
browser window.
SUBJECT : Programming Skills – IV (Java)
(.. 48 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
import java.awt.*;
import java.net.*;
import java.applet.*;
import java.awt.event.*;
public class prog_30 extends Applet implements ActionListener
{
TextField urlField;
Button goButton;
boolean UrlOnError;
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)
{
if (!UrlOnError)
{
g.drawString("Type your URL and click go!",20,80);
}
else
{
g.drawString("Malformed URL: "+userUrl,20,80);
g.drawString("This Applet only allows .com domains",20,100);
}
}
public void actionPerformed(ActionEvent act)
{
UrlOnError = false; String temp = urlField.getText();
if (temp.length() > 6)
{
if (!temp.substring(0,7).toUpperCase().equals("HTTP://"))
temp = "Http://" + temp;
}
Else
{
temp = "Http://" + temp;
if (temp.indexOf(".com") == -1)
{
UrlOnError = true;
}
try
{
userUrl = new URL(temp);
}
catch (Exception e)
{
UrlOnError = true;
SUBJECT : Programming Skills – IV (Java)
(.. 49 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
}
urlField.setText(userUrl.toString());
if (!UrlOnError)
{
getAppletContext().showDocument(userUrl,"_blank");
}
repaint();
}
}
Program-22
Create a class called Stem and Leaf, which should have a provision to maintain the stem size andthe number of intervals between
the two stems. It should also have a method to load the data fromthe file and a method to display the stem-and-leaf diagram for
the loaded data. Test the class to display data regarding the marks of students of your class in the previous exam.
import java.io.*;
import java.util.Formatter;
/*
this is stamp_leaf.csv file data that we have create manually.....(SV)
12,112,72,69,97,107,73,126,82,92,115,95,84,68,100,92,128,104,108,76,141,119,98,85,
76,118,132,96,91,81,113,115,94,86,127,134,100,102,80,98,106,106,73,124,83,92,81,10
6,75,95,119
*/
class StemAndLeaf {
int data[]=null;
StemAndLeaf() {
data=new int[50];
}
void loadFromCSV(FileInputStream fin) throws IOException {
int ch,i,j=0,num=0;
do {
i = fin.read();
if(i != -1) {
if(i == 44) {
data[j]=num;
j++;
num=0;
} else {
num*=10;
ch=i-48;
num+=ch;
}
}
} while(i != -1);
data[j]=num;
fin.close();
}
void display() {
Formatter f;
boolean flag=true;
int stm[]=new int[9]; // 9 means no of stamp value
int lf[][]=new int[9][11]; // 11 means no leaf in per stamp
int k=0,m=0;
for(int i=0;i<stm.length;i++) {
stm[i]=-1;
SUBJECT : Programming Skills – IV (Java)
(.. 50 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
for(int j=0;j<lf[i].length;j++)
lf[i][j]=-1;
}
for(int i=0;i<data.length;i++) {
flag=true;
for(int j=0;j<stm.length;j++) {
if((data[i]/10) == stm[j]) {
flag=false;
break;
}
}
if(flag && data[i]!=0) {
stm[k]=(data[i]/10);
k++;
}
}
for(int i=0;i<stm.length-1;i++) {
for(int j=i+1;j<stm.length;j++) {
if(stm[i]>stm[j]) {
int temp=stm[i];
stm[i]=stm[j];
stm[j]=temp;
}
}
}
for(k=0;k<stm.length;k++) {
m=0;
for(int i=0;i<data.length;i++) {
if(stm[k]==(data[i]/10) && data[i]!=0 && stm[k]!=-1) {
lf[k][m]=data[i]%10;
m++;
}
}
}
for(k=0;k<stm.length;k++) {
for(int i=0;i<lf[k].length-1;i++) {
for(int j=i+1;j<lf[k].length;j++) {
if(lf[k][i]>lf[k][j]) {
int temp=lf[k][i];
lf[k][i]=lf[k][j];
lf[k][j]=temp;
}
}
}
}
for(k=0;k<stm.length;k++) {
f=new Formatter();
f.format("%2d",stm[k]);
System.out.print(f);
System.out.print(" I ");
for(int i=0;i<lf[k].length;i++)
if(lf[k][i]!=-1)
System.out.print(lf[k][i]+" ");
System.out.println();
}
}
}
class Prog22 {
public static void main(String args[]) throws IOException {
SUBJECT : Programming Skills – IV (Java)
(.. 51 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
StemAndLeaf sl=new StemAndLeaf();
FileInputStream fin;
try {
fin = new FileInputStream("stamp_leaf.csv");
}
catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
}
sl.loadFromCSV(fin);
sl.display();
}
}
Program 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 toload values from a file regarding the variables. eg. We
consider two variables as percentage ofmarks in GCET exam and percentage of marks in 1st year of MCA, Provide methods in the
class tocompute the correlation coefficient between any two variables, specified in the parameter. Test theclass by computing
the correlation coefficient between the marks of GCET and marks of 1st yearMCA for students of your class.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
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;
SUBJECT : Programming Skills – IV (Java)
(.. 52 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
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);
sb=Math.sqrt(sb);
cor_coef=sab/sa*sb;
System.out.println("correlation co-efficient: " + cor_coef);
}
}
class Prog_24
{
public static void main(String args[])
{
StatisticalData x=new StatisticalData();
x.get();
x.correl_coeff();
}
}
Program 29:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class StatisticalData
{
int v1[],v2[];
String v1name,v2name;
public StatisticalData()
{
v1=new int[5];
v2=new int[5];
v2name="str2";
}
public void get()
{
int i;
SUBJECT : Programming Skills – IV (Java)
(.. 53 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
for(i=0;i<5;i++)
{
v1[i]=i*2;
}
for(i=0;i<5;i++)
{
v2[i]=i*5;
}
}
public int correl_coeff(int x)
{
int i;
for(i=0;i<5;i++)
{
return v1[x];
}
return 0;
}
public double correl_ans()
{
double d,m1=0,m2=0,tatb=0,sab,ta2=0,tb2=0,sa,sb,cor_coef;
int i;
for(i=0;i<5;i++)
{
m1=m1+v1[i];
m2=m2+v2[i];
}
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);
sb=Math.sqrt(sb);
cor_coef=sab/sa*sb;
return cor_coef;
}
public int correl_coeff2(int x)
{
for(int i=0;i<5;i++)
{
return v2[x];
}
return 0;
}
}
public class prog28{
public static void main(String[] args){
int i;
StatisticalData x=new StatisticalData();
x.get();
Integer temp;
Double ans;
SUBJECT : Programming Skills – IV (Java)
(.. 54 ..)
PATEL GROUP OF INSTITUTIONS - MEHSANA
:: MCA – III ::
JFrame jf = new JFrame("Inventory");
Container c = jf.getContentPane();
Object[] colnames = {"H1","H2"};
Object[][] data=new Object[10][10];
for(i=0;i<5;i++)
{
temp=x.correl_coeff(i);
data[i][0]=temp;
}
for(i=0;i<5;i++)
{
temp=x.correl_coeff2(i);
data[i][1]=temp;
}
ans=x.correl_ans();
data[i][0]="Correlation";
data[i][1]=ans;
jf.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
JTable jt = new JTable(data, colnames);
JScrollPane scrollableTable = new JScrollPane(jt);
c.add(scrollableTable);
jf.setSize(500, 150);
jf.setVisible(true);
}
}
SUBJECT : Programming Skills – IV (Java)
(.. 55 ..)
Download