Java Codes 1.0

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Java codes

Assignment 1
Exercise:
SET A
a) Write a program to calculate perimeter and area of rectangle. (hint : area = length * breadth , perimeter=2*(length+breadth))
import java.io.*;
import java.util.*;
class ass1a1
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
double l,b;
double p,a;
System.out.println("\nEnter the length of rectangle: ");
l=Double.parseDouble(sc.next());
System.out.println("\nEnter the breadth of rectangle: ");
b=Double.parseDouble(sc.next());
p=2*(l+b);
a=l*b;
System.out.println("\n Area= "+a+"sq units");
System.out.println("\n Perimeter= "+p+"units");
}
}
b) Write a menu driven program to perform the following operations i. Calculate the volume of cylinder. (hint : Volume: π × r² × h)
ii. Find the factorial of given number. iii. Check the number is Armstrong or not. iv. Exit
import java.io.*;
import java.util.*;
class ass1a2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int ch,n,i,p=1,num,temp=0;
double r,h,v;
System.out.print("\nMenu\n");
System.out.println("\n1. Calculate volume of cylinder\n2. Find the factorial of given number\n3. Check the number is Armstrong
or not\n4. Exit");
System.out.println("\n Enter your choice: ");
ch=Integer.parseInt(sc.next());
switch(ch)
{
case 1:System.out.println("Enter the radius of cylinder: ");
r=Double.parseDouble(sc.next());
System.out.println("Enter the height of cylinder: ");
h=Double.parseDouble(sc.next());
v=3.142*r*r*h;
System.out.println("Volume: "+v+"cu units");
break;
case 2:
System.out.println("Enter the number: ");
n=Integer.parseInt(sc.next());
for(i=1;i<=n;i++)
{
p=p*i;
}
System.out.println("Factorial: "+p);
break;
case 3:
Sytem.out.println("Enter the number: ");
num=Integer.parseInt(sc.next());
while(num!=0)
{
temp=num%10;
sum=sum+(temp*temp*temp);
num=num/10;
}
if
Sytem.out.println("");
break;
case 4:System.out.println("Exit");
break;
}
}
c) Write a program to accept the array element and display in reverse order.
import java.io.*;
import java.util.*;
public class ass1a3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,n;
int a[]=new int[10];
System.out.println("Enter the size of array: ");
n=sc.nextInt();
System.out.println("Enter the elements: ");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Array elements in reverse order: ");
for(i=n-1;i>=0;i--)
{
System.out.println(a[i]);
}
}
}
SET B a) Write a java program to display the system date and time in various formats shownbelow: Current date is : 31/08/2021
Current date is : 08-31-2021 Current date is : Tuesday August 31 2021 Current date and time is : Fri August 31 15:25:59 IST 2021
Current date and time is : 31/08/21 15:25:59 PM +0530 Current time is : 15:25:59 Current week of year is : 35 Current week of
month : 5 Current day of the year is : 243 Note: Use java.util.Date and java.text.SimpleDateFormat class
import java.text.SimpleDateFormat;
import java.util.Date;
class ass1b1
{
public static void main(String[] args)
{
SimpleDateFormat sd=new SimpleDateFormat ("dd/MM/yyyy");
String d1=sd.format(new Date());
System.out.println("Date: "+d1);
sd=new SimpleDateFormat ("MM-dd-yyyy");
d1=sd.format(new Date());
System.out.println("Date: "+d1);
sd=new SimpleDateFormat ("EEEEEEEEE MMMMM dd yyyy");
d1=sd.format(new Date());
System.out.println("Date: "+d1);
sd=new SimpleDateFormat ("EEE MMMMM dd HH:mm:ss z yyyy");
d1=sd.format(new Date());
System.out.println("Date and time: "+d1);
sd=new SimpleDateFormat ("dd/MM/yyyy HH:mm:ss a SSSZ");
d1=sd.format(new Date());
System.out.println("Date and time: "+d1);
sd=new SimpleDateFormat ("HH:mm:ss");
d1=sd.format(new Date());
System.out.println("Time: "+d1);
sd=new SimpleDateFormat ("w");
d1=sd.format(new Date());
System.out.println("Current week: "+d1);
sd=new SimpleDateFormat ("W");
d1=sd.format(new Date());
System.out.println("Week of the month: "+d1);
sd=new SimpleDateFormat ("D");
d1=sd.format(new Date());
System.out.println("Day of the year: "+d1);
}
}

b) Define a class MyNumber having one private int data member. Write a default constructor to initialize it to 0 and another
constructor to initialize it to a value (Use this). Write methods isNegative, isPositive, isZero, isOdd, isEven. Create an object in
main. Use command line arguments to pass a value to the object (Hint : convert string argument to integer) and perform the
above tests. Provide javadoc comments for all constructors and methods and generate the html help file.
import java.io.*;
import java.util.*;
public class MyNumber
{
private int x;
public MyNumber()
{
x=0;
}
public MyNumber(int x)
{
this.x=x;
}
public void isNegative()
{
if(x<0)
System.out.println(x+" Is Negative");
}
public void isPositive()
{
if(x>0)
System.out.println(x+" Is Positive");
}
public void isZero()
{
if(x==0)
System.out.println(x+" Is Zero");
}
public void isOdd()
{
if(x%2!=0)
System.out.println(x+" Is Odd");
}
public void isEven()
{
if(x%2==0)
System.out.println(x+" Is Even");
}//main
public static void main(String[] args)
{
int n;
n=Integer.parseInt(args[0]);
MyNumber x1=new MyNumber(n);
x1.isNegative();
x1.isPositive();
x1.isZero();
x1.isOdd();
x1.isEven();
}
}
c) Write a menu driven program to perform the following operations on 2D array: i. Sum of diagonal elements ii. Sum of upper
diagonal elements iii. Sum of lower diagonal elements iv. Exit
import java.io.*;
import java.util.*;
class ass1b3
{
public static void main(String[] args)
{
int i,j,n,r,c,ch;
int sum=0,sum1=0,sum2=0;
int a[][]=new int[10][10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no of rows: ");
r=sc.nextInt();
System.out.println("Enter the no of columns: ");
c=sc.nextInt();
System.out.println("Enter the elements of array: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Array");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.print("\n");
}
System.out.println("Menu");
System.out.println("1.Sum of diagonal elements\n2.Sum of upper diagonal elements\n3.Sum of lower diagonal
elements\n4.Exit\n");
do
{
System.out.println("Enter your choice");
ch=sc.nextInt();
switch(ch)
{
case 1:
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(i==j)
{
sum=sum+a[i][j];
}
}
}
System.out.println("Sum of Diagonal elements: "+sum);
break;
case 2:
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(i<j)
{
sum1=sum1+a[i][j];
}
}
}
System.out.println("Sum of Upper Diagonal elements: "+sum1);
break;
case 3:
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(i>j)
{
sum2=sum2+a[i][j];
}
}
}
System.out.println("Sum of Lower Diagonal elements: "+sum2);
break;
case 4:
break;
}
}while(ch!=4);
}
}
Assignment 2
Exercise
SET A:
a) Create an employee class(id,name,deptname,salary). Define a default and parameterized constructor. Use ‘this’ keyword to
initialize instance variables. Keep a count of objects created. Create objects using parameterized constructor and display the
object count after each object is created.(Use static member and method). Also display the contents of each object.
import java.io.*;
import java.util.*;
class ass2a1
{
int id;String name;String dname;double salary;
static int cnt=0;
public ass2a1(int id,String name,String dname,double salary)throws IOException
{
this.id=id;
this.name=name;
this.dname=dname;
this.salary=salary;
cnt++;
}
static int recnt()
{
return cnt;
}
public static void main(String[] args)throws IOException
{
int i,n;
int id;
String name,dname;
double salary;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of employees: ");
n=Integer.parseInt(br.readLine());
ass2a1[] e=new ass2a1[n];
for(i=0;i<n;i++)
{
System.out.println("Enter the employee id: ");
id=Integer.parseInt(br.readLine());
System.out.println("Enter employee name: ");
name=br.readLine();
System.out.println("Enter department: ");
dname=br.readLine();
System.out.println("Enter salary: ");
salary=Double.parseDouble(br.readLine());
e[i]=new ass2a1(id,name,dname,salary);
System.out.println("Count "+recnt());
}
for(i=0;i<n;i++)
{
System.out.println("Id:"+e[i].id+"\tName:"+e[i].name+"\tDepartment:"+e[i].dname+"\tSalary:"+e[i].salary);
}
}
}

b) Define Student class(roll_no, name, percentage) to create n objects of the Student class. Accept details from the user for each
object. Define a static method “sortStudent” which sorts the array on the basis of percentage.
import java.io.*;
public class student1
{
int rno;
String name;
int per;
public student1(int rno,String name,int per)//Parameterized constructor
{
this.rno=rno;
this.name=name;
this.per=per;
}

public static void main(String args[]) throws IOException


{
int n,i,rno;
String name;
int per;
System.out.println("Enter the number of students: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
student1[] st=new student1[n];//Not created objects yet
for(i=0;i<n;i++)
{
System.out.println("Enter the Student's roll no: ");
rno=Integer.parseInt(br.readLine());
System.out.println("Enter the Student's Name: ");
name=br.readLine();
System.out.println("Enter the Student's percentage: ");
per=Integer.parseInt(br.readLine());
st[i]=new student1(rno,name,per);
}

for(i=0;i<n;i++)
{
System.out.println("Student Roll No = " +st[i].rno);
System.out.println("Student Name = " +st[i].name);
System.out.println("Student Percentage = " +st[i].per);
}

sort(st,n);
}

public static void sort(student1[] st,int n)


{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(st[i].per>st[j].per)
{
temp=st[i].per;
st[i].per=st[j].per;
st[j].per=temp;
}
}
}

System.out.println("\nArray after Sorting: ");


for(i=0;i<n;i++)
{
System.out.println("\nPercentage = " +st[i].per+"\t roll no ="+st[i].rno+"\t name="+st[i].name);
}
}

c) Write a java program to accept 5 numbers using command line arguments sort and display them.
import java.io.*;
class ass2a3
{
public static void main(String args[])
{
int i,j,temp;
int[] num=new int[5];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(i=0;i<5;i++)
{
num[i]=Integer.parseInt(args[i]);
}
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
for(i=0;i<5;i++)
{
System.out.print("\t"+num[i]);
}
}
}
d) Write a java program that take input as a person name in the format of first, middle and last name and then print it in the form
last, first and middle name, where in the middle name first character is capital letter.
import java.io.*;
class ass2a4
{
public static void main(String[] args)throws IOException
{
String str;
String res="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name: ");
str=br.readLine();
String s[]=str.split(" ");

res=(s[2]+" "+s[0]+" "+s[1].substring(0,1).toUpperCase()+s[1].substring(1));


System.out.println(res);
}
}
SET B: a) Write a Java program to create a Package "SY" which has a class SYMarks (members - ComputerTotal, MathsTotal, and
ElectronicsTotal). Create another package TY which has a class TYMarks (members - Theory, Practicals). Create n objects of
Student class (having rollNumber, name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects and calculate the
Grade ('A' for >= 70, 'B' for >= 60 'C' for >= 50 , Pass Class for > =40 else 'FAIL') and display the result of the student in proper
format.
Symk.java
package sy;
import java.io.*;
public class symk
{
int ct,mt,et;
public void sy_assign()throws IOException
{
System.out.println("\n enter marks of students for computer(ct),maths(mt) and electronics(et) out of 200:");
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
ct=Integer.parseInt(br.readLine());
mt=Integer.parseInt(br.readLine());
et=Integer.parseInt(br.readLine());
}

public void sy_display()


{
System.out.println("\n total in computer sub:"+ct);
System.out.println("\n total in maths sub:"+mt);
System.out.println("\n total in electronic sub:"+et);
}
//return totalofcomp
public int sytot()
{
return ct;
}
}

Tymk.java
package ty;
import java.io.*;
public class tymk
{
int[] tm=new int[8];
int[] pm=new int[3];
int t1,t2;

public void ty_assign()throws IOException


{
int i;
t1=0;
t2=0;
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter theory and practical marks::");
for(i=0;i<8;i++)
{
System.out.println("enter the theory::"+(i+1));
tm[i]=Integer.parseInt(br.readLine());
t1=tm[i]+t1;
}

for(i=0;i<3;i++)
{
System.out.println("enter the practicals::"+(i+1));
pm[i]=Integer.parseInt(br.readLine());
t2=pm[i]+t2;
}
}
public void ty_display()
{
System.out.println("\n total theory marks"+t1);
System.out.println("\n total practical marks"+t2);
}

public int tytot()


{
return t1+t2;
}
}
Ass2.java
import ty.*;
import sy.*;
import java.io.*;
import java.util.*;
public class Ass2
{
int rollno,stot,ttot;
float per;
String name;
public Ass2(int rollno,String name)
{
this.rollno=rollno;
this.name=name;
}
public static void main(String[] args) throws IOException
{
int cnt,rollno,i,per;
String name,grade;
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter no of students:");
cnt=Integer.parseInt(br.readLine());
Ass2[] S=new Ass2[cnt];

for(i=0;i<cnt;i++)
{
System.out.println("enter roll no and name of student:");
rollno=Integer.parseInt(br.readLine());
name=br.readLine();
S[i]=new Ass2(rollno,name);
symk s=new symk();
tymk t=new tymk();
s.sy_assign();
S[i].stot=s.sytot();
t.ty_assign();
S[i].ttot=t.tytot();
S[i].per=(float)(S[i].stot+S[i].ttot)/1600*100;

if(S[i].per>=70)
System.out.println("Rollno"+S[i].rollno+"Name"+S[i].name+"Percent"+S[i].per+"\tGrade A");
else if(S[i].per>=60)
System.out.println("Rollno"+S[i].rollno+"Name"+S[i].name+"Percent"+S[i].per+"\tGrade B");
else if(S[i].per>=50)
System.out.println("Rollno"+S[i].rollno+"Name"+S[i].name+"Percent"+S[i].per+"\tGrade C");
else if(S[i].per>=40)
System.out.println("Rollno"+S[i].rollno+"Name"+S[i].name+"Percent"+S[i].per+"\tGrade D");
else
System.out.println("Rollno"+S[i].rollno+"Name"+S[i].name+"Percent"+S[i].per+"\tfail");
}
}
}

b) Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg). Create an array of n player objects
.Calculate the batting average for each player using static method avg(). Define a static sort method which sorts the array on the
basis of average. Display the player details in sorted order.
import java.io.*;
class ass2b2
{
String name;
int innings,notout,totalruns;
double bat_avg;
public ass2b2(String name,int innings,int notout,int totalruns)
{
this.name=name;
this.innings=innings;
this.notout=notout;
this.totalruns=totalruns;
}
static void bat_avg(int n,ass2b2[] a)
{
int i;
for(i=0;i<n;i++)
{
a[i].bat_avg=(a[i].totalruns/a[i].innings);
}
}
static void sort(int n,ass2b2[] a)
{
int i,j;
double temp;
String temp1;
int temp2,temp3,temp4;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i].bat_avg<a[j].bat_avg)
{
temp=a[i].bat_avg;
a[i].bat_avg=a[j].bat_avg;
a[j].bat_avg=temp;

temp1=a[i].name;
a[i].name=a[j].name;
a[j].name=temp1;

temp2=a[i].innings;
a[i].innings=a[j].innings;
a[j].innings=temp2;
temp3=a[i].notout;
a[i].notout=a[j].notout;
a[j].notout=temp3;

temp4=a[i].totalruns;
a[i].totalruns=a[j].totalruns;
a[j].totalruns=temp4;
}
}
}
}
public static void main(String[] args)throws IOException
{
int n,i;
String name;
int innings,notout,totalruns;
double bat_avg;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the no of players: ");
n=Integer.parseInt(br.readLine());
ass2b2[] a=new ass2b2[n];
for(i=0;i<n;i++)
{
System.out.println("Enter name: ");
name=br.readLine();
System.out.println("Enter the number of innings: ");
innings=Integer.parseInt(br.readLine());
System.out.println("Enter the number of times not out: ");
notout=Integer.parseInt(br.readLine());
System.out.println("Enter the total runs: ");
totalruns=Integer.parseInt(br.readLine());
a[i]=new ass2b2(name,innings,notout,totalruns);
}
bat_avg(n,a);
sort(n,a);
for(i=0;i<n;i++)
{
System.out.println("Name:"+a[i].name+"\tInnings:"+a[i].innings+"\tnot out:"+a[i].notout+"\tTotal
runs:"+a[i].totalruns+"\tAverage:"+a[i].bat_avg);
}
}
}

Assignment 3
Exercise:
SET A
: a) Write a program for multilevel inheritance such that country is inherited from continent. State is inherited from country.
Display the place, state, country and continent.

import java.io.*;
import java.lang.*;
import java.util.*;
public class Asetaa
public static void main(String[] args)throws IOException
{
String c;
String c1;
String s;
String p;
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter continent:");
c=br.readLine();
System.out.println("enter country:");
c1=br.readLine();
System.out.println("enter state:");
s=br.readLine();
System.out.println("enter place name :");
p=br.readLine();

System.out.println("\n\n continent:"+c);
System.out.println("\nCountry:"+c1);
System.out.println("\nState:"+s);
System.out.println("\nplace:"+p);
}

class Continent
{
String c;
public Continent(String c)
{
this.c=c;
}
void display()
{
System.out.println("\n\n continent name:"+c);
}

class Country extends Continent


{
String c1;
public Country(String c,string c1)
{
super(c);
this.c1=c1;
}
void display()
{
super.display();
System.out.println("\n\n country name:"+c1);
}
}

class State extends Country


{
String s;
public State(String c,string c1,String s)
{
super(c1,c);
this.s=s;
}
void display()
{
super.display();
//System.out.println("\n\n continent:"+c);
System.out.println("\n\n state:"+s);
}
}

class Place extends State


{
String p;
public Place(String c,string c1,String s,String p)
{
super(s,c1,c);
this.p=p;
}
void display()
{
super.display();
System.out.println("\n\n place:"+p);
}
}
}

b) Define an abstract class Staff with protected members id and name. Define a parameterized constructor. Define one subclass
OfficeStaff with member department. Create n objects of OfficeStaff and display all details.
import java.io.*;
import java.util.*;

abstract class Staff{


protected int id;
protected String name;
public Staff(int id,String name)
{
this.id=id;
this.name=name;
}
}
class OfficeStaff extends Staff{
String department;
public OfficeStaff(String department,int id,String name)
{
super(id,name);
this.department=department;
}

void display()
{
System.out.println(id+"\t"+name+"\t"+department);
}
public static void main(String[] args)throws IOException
{
int i,n,id;
String name;
String department;
System.out.println("Enter the number of employees: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
OfficeStaff[] ob=new OfficeStaff[n];
for(i=0;i<n;i++)
{
System.out.println("Enter the id: ");
id=Integer.parseInt(br.readLine());
System.out.println("Enter the name: ");
name=br.readLine();
System.out.println("Enter the department: ");
department=br.readLine();
ob[i]=new OfficeStaff(department,id,name);
}
System.out.println("ID\tName\tDepartment");
for(i=0;i<n;i++)
{
ob[i].display();
}
}
}

c) Define an interface "Operation" which has methods area(),volume().Define a constant PI having a value 3.142.Create a class
cylinder which implements this interface (members - radius, height) Create one object and calculate the area and volume.
import java.io.*;
public interface Operation{
final double PI=3.142;
double area();
double volume();
}
class Cylinder implements Operation{
double r,h;
public Cylinder(double r,double h)
{
this.r=r;
this.h=h;
}
public double area()
{
double a;
a=2*PI*r*(r+h);
return a;
}
public double volume()
{
double v;
v=PI*r*r*h;
return v;
}
public static void main(String[] args)throws IOException
{
double r,h;
double ar,vol;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter radius: ");
r=Double.parseDouble(br.readLine());
System.out.println("Enter height: ");
h=Double.parseDouble(br.readLine());
Cylinder ob=new Cylinder(r,h);
ar=ob.area();
vol=ob.volume();
System.out.println("Area: "+ar+"\nVolume: "+vol);
}
}

d) Write a program to find the cube of given number using function interface.

import java.util.*;
import java.io.*;
interface Cube{
int calculate(int x);
}
class Test
{
public static void main(String []args)throws IOException
{
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter number to find cube:");
int a=Integer.parseInt(br.readLine());
cube s=(int x)->x*x*x;
int ans=s.calculate(ans);
System.out.println(" cube:"+ans);
}
}

SET B:
a) Create an abstract class “order” having members id,description.Create two subclasses “Purchase Order” and “Sales Order”
having members customer name and Vendor name respectively.Define methods accept and display in all cases. Create 3 objects
each of Purchase Order and Sales Order and accept and display details.

//order assignemtn 3 set b q)a


import java.io.*;
import java.lang.*;
import java.util.*;
abstract class Order
{
int id;
String desp;
abstract void accept();
abstract void display();
}
class Purchaseorder extends Order
{
String cusname;

void accept()
{
try
{
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter purchase order details");
System.out.println("enter id,enter description ,enter customer name :");
id=Integer.parseInt(br.readLine());
desp=br.readLine();
cusname=br.readLine();
}
catch(Exception e)
{
System.out.println("exception caught ");
}
}
void display()
{
System.out.println("purchase details");
System.out.println("id:"+id);
System.out.println(" description :"+desp);
System.out.println(" customer name:"+cusname);
}
}

class Salesorder extends Order


{
String venname;
void accept()
{
try
{
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter sales order details");
System.out.println("enter id,enter description ,enter vendor name :");
id=Integer.parseInt(br.readLine());
desp=br.readLine();
venname=br.readLine();
}
catch(Exception e1)
{
System.out.println("exception 2 caught ");
}
}
void display()
{
System.out.println("sales details");
System.out.println("id:"+id);
System.out.println(" description :"+desp);
System.out.println(" vendor name:"+venname);
}
}

public class Assetba


{
int id;
String desp,cusname,venname;
public Assetba(int id,String desp,String cusname,String venname)
{
this.id=id;
this.desp=desp;
this.cusname=cusname;
this.venname=venname;
}
public static void main (String[] args)throws IOException
{
int i,ch;
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
do
{
System.out.println("\n 1.Purchase order\n 2.Sales order \n 3.Exit\n");
System.out.println("enter your choice of order :");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: Order[] p= new Purchaseorder[3];/*Purchaseorder p[]=new Purchaseorder[3];*/
for(i=0;i<3;i++)
{
p[i]=new Purchaseorder();
p[i].accept();
}
for(i=0;i<3;i++)
{
p[i].display();
}
break;

case 2: Order[] s= new Salesorder[3];/*Salesorder s[]=new Salesorder[3];*/


for(i=0;i<3;i++)
{
s[i]=new Salesorder();
s[i].accept();
}
for(i=0;i<3;i++)
{
s[i].display();
}
break;
}
}
while(ch!=3);
}
}

b) Write a program to using marker interface create a class product(product_id, product_name, product_cost, product_quantity)
define a default and parameterized constructor. Create objects of class product and display the contents of each object and Also
display the object count.
import java.io.*;
interface Product1
{
}
class Product implements Product1{
int id,quantity;
String name;
double cost;
public Product(int id,String name,double cost,int quantity)
{
this.id=id;
this.name=name;
this.cost=cost;
this.quantity=quantity;
}
public static void main(String[] args)throws IOException
{
int n,i,count=0;
int id,quantity;
String name;
double cost;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of products: ");
n=Integer.parseInt(br.readLine());
Product p[]=new Product[n];
for(i=0;i<n;i++)
{
System.out.println("Enter product id: ");
id=Integer.parseInt(br.readLine());
System.out.println("Enter product name: ");
name=br.readLine();
System.out.println("Enter the quantity: ");
quantity=Integer.parseInt(br.readLine());
System.out.println("Enter the cost: ");
cost=Double.parseDouble(br.readLine());
p[i]=new Product(id,name,cost,quantity);
count++;
}
if(p[0] instanceof Product1)
{
System.out.println("Product Marker Interface");
}
System.out.println("ID\tName\tCost\tQuantity");
for(Product p1:p)
{
System.out.println(p1.id+"\t"+p1.name+"\t"+p1.cost+"\t"+p1.quantity);
}
System.out.println("Count: "+count);
}
}

Assignment 4
Exercise:
SET A:
a) Define a class patient (patient_name, patient_age, patient_oxy_level,patient_HRCT_report). Create an object of patient.
Handle appropriate exception while patient oxygen level less than 95% and HRCT scan report greater than 10, then throw user
defined Exception “Patient is Covid Positive(+) and Need to Hospitalized” otherwise display its information.

import java.io.*;
class CovidException extends Exception{
public CovidException(){
System.out.println("Patient is Covid Positive and needs to be hospitalized");
}
}
class Patient{
String name;
int age;
double level,hrct;
public Patient(String name,int age,double level,double hrct)
{
this.name=name;
this.age=age;
this.level=level;
this.hrct=hrct;
}
public static void main(String[] args)throws IOException
{
String name;
int age;
double level,hrct;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name: ");
name=br.readLine();
System.out.println("Enter the age: ");
age=Integer.parseInt(br.readLine());
System.out.println("Oxygen level: ");
level=Double.parseDouble(br.readLine());
System.out.println("HRCT report: ");
hrct=Double.parseDouble(br.readLine());
Patient ob=new Patient(name,age,level,hrct);
try{
if(ob.level<95 && ob.hrct>10)
throw new CovidException();
else
System.out.println("Patient Info: \n"+"Name: "+ob.name+"\nAge: "+ob.age+"\nHRCT report: "+ob.hrct+"\nOxygen level:
"+ob.level);
}catch(CovidException e){
}

}
}

b) Write a program to read a text file “sample.txt” and display the contents of a file in reverse order and also original contents
change the case (display in upper case).

import java.io.*;
import java.util.*;
class ass4a2{
public static void main(String[] args)throws IOException
{
FileReader file=new FileReader("a.txt");
Scanner sc=new Scanner(file);
String s;
while(sc.hasNext())
{
StringBuffer sb=new StringBuffer();
s=sc.next();
String s1=s.toUpperCase();
sb.append(s1);
sb.reverse();
System.out.println(sb);
}
}
}

c) Accept the names of two files and copy the contents of the first to the second. First file having Book name and Author name in
file. Second file having the contents of First file and also add the comment ‘end of file’ at the end.
import java.io.*;
import java.util.*;
class ass4a3{
public static void main(String[] args)throws IOException
{
int c;
String f1,f2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter name of first file: ");
f1=sc.next();
System.out.println("Enter name of second file: ");
f2=sc.next();
FileReader fr=new FileReader(f1);
FileWriter fw=new FileWriter(f2,true);
while((c=fr.read())!=-1)
{
fw.write(c);
}
fw.append("\nEND OF FILE");
fr.close();
fw.close();
}
}

SET B:

a) Write a program to read book information (bookid, bookname, bookprice, bookqty) in file “book.dat”. Write a menu driven
program to perform the following operations using Random access file: i. Search for a specific book by name. ii. Display all book
and total cost

import java.io.*;
import java.util.*;
class ass4b1{
public static void main(String[] args)throws IOException
{
String name,line;
int cost=0,ch,flag=0,i,tcost=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
File f=new File("book.dat");
RandomAccessFile rf=new RandomAccessFile(f,"rw");
do{
System.out.println("MENU");
System.out.println("1.Search\n2.Display book and total cost");
System.out.println("Enter your choice: ");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
rf.seek(0);
System.out.println("Enter book name to search: ");
name=br.readLine();
while(rf.getFilePointer()!=f.length())
{
line=rf.readLine();
String a[]=line.split(" ");
if(a[1].equals(name))
{
System.out.println("Book available");
flag=1;
break;
}
else
flag=2;
}
if(flag==2)
System.out.println("Book Unavailable");
break;
case 2:
rf.seek(0);
while(rf.getFilePointer()!=f.length())
{
line=rf.readLine();
String a[]=line.split(" ");
cost=cost+(Integer.parseInt(a[2])*Integer.parseInt(a[3]));
System.out.println(a[1]+"\t"+cost);
tcost=tcost+(Integer.parseInt(a[2])*Integer.parseInt(a[3]));
}
System.out.println("Total cost\t"+tcost);
break;
}
}while(ch!=2);
}
}

b) Define class EmailId with members, username and password. Define default and parameterized constructors. Accept values
from the command line Throw user defined exceptions – “InvalidUsernameException” or “InvalidPasswordException” if the
username and password are invalid. c) Write a java program to accept Employee name from the user and check whether it is valid
or not. If it is not valid then throw user defined Exception “Name is Invalid” otherwise display it.(Name should contain only
characters).

import java.io.*;
class InvalidUsernameException extends Exception{
public InvalidUsernameException(){
System.out.println("Invalid Username");
}
}
class InvalidPasswordException extends Exception{
public InvalidPasswordException(){
System.out.println("Invalid Password");
}
}
class EmailId{
String uname,pwd;
public EmailId()
{
uname="";
pwd="";
}
public EmailId(String uname,String pwd)
{
this.uname=uname;
this.pwd=pwd;
}
public static void main(String[] args)
{
String uname,pwd;
uname=args[0];
pwd=args[1];
EmailId ob=new EmailId(uname,pwd);

try{
if(("mahebshaikh").equals(ob.uname))
System.out.println("Valid Username");
else
throw new InvalidUsernameException();
}catch(InvalidUsernameException e){ }

try{
if(("maheb1234").equals(ob.pwd))
System.out.println("Valid Password");
else
throw new InvalidPasswordException();
}catch(InvalidPasswordException e1){ }

}
}

Assignment 5

Exercise:
SET A:

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

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener
{
JButton one,two,three,four,five,six,seven,eight,nine,zero,eq,dot,add,sub,mul,div;
JTextField t1;
JPanel p1,p2;
float op1,op2;
char oper;
float ans=0;
public Calculator()
{
one=new JButton("1");
two=new JButton("2");
three=new JButton("3");
four=new JButton("4");
five=new JButton("5");
six=new JButton("6");
seven=new JButton("7");
eight=new JButton("8");
nine=new JButton("9");
zero=new JButton("0");
dot=new JButton(".");
add=new JButton("+");
sub=new JButton("-");
mul=new JButton("*");
div=new JButton("/");
eq=new JButton("=");

t1=new JTextField(20);

p1=new JPanel();
p1.setLayout(new BorderLayout());
p1.add(t1,BorderLayout.NORTH);

p2=new JPanel();
p2.setLayout(new GridLayout(4,4));
p2.add(one);
p2.add(two);
p2.add(three);
p2.add(add);
p2.add(four);
p2.add(five);
p2.add(six);
p2.add(sub);
p2.add(seven);
p2.add(eight);
p2.add(nine);
p2.add(mul);
p2.add(zero);
p2.add(dot);
p2.add(eq);
p2.add(div);

one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
zero.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
eq.addActionListener(this);
dot.addActionListener(this);
setLayout(new GridLayout(2,1));
add(p1);
add(p2);

setSize(500,200);
setVisible(true);
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
String nm=(String)ae.getActionCommand();
if(nm.equals("1")||nm.equals("2")||nm.equals("3")||nm.equals("4")||nm.equals("5")||nm.equals("6")||nm.equals("7")||nm.e
quals("8")||nm.equals("9")||nm.equals("0")||nm.equals("."))
{
String s=t1.getText();
t1.setText(s+nm);
}
JButton b=(JButton)ae.getSource();
if(b==add||b==sub||b==mul||b==div)
{
op1=Float.parseFloat(t1.getText());
t1.setText("");
t1.requestFocus();
oper=b.getLabel().charAt(0);
}
if(b==eq)
{
op2=Float.parseFloat(t1.getText());
switch(oper)
{
case '+':
ans=op1+op2;
break;

case '-':
ans=op1-op2;
break;

case '*':
ans=op1*op2;
break;

case '/':
ans=op1/op2;
break;
}
t1.setText(Float.toString(ans));
}
}
public static void main(String[] args)
{
new Calculator();
}
}
b) Design a screen to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICK and display the position of the
Mouse_Click in a TextField.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Mouse extends JFrame{
JPanel p1;
JTextField t;
Mouse(){
p1=new JPanel();
t=new JTextField(20);
p1.add(t,BorderLayout.CENTER);
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
t.setText("Clicked at: ("+e.getX()+","+e.getY()+")");
repaint();
}
});

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

addMouseMotionListener(new MouseAdapter()
{
public void mouseMoved(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
t.setText("X= "+x+" Y="+y);
}
});
add(p1);
setSize(500,500);
setVisible(true);
}
public static void main(String[] args)
{
new Mouse();
}
}

c) Write Java program to design three text boxes and two buttons using swing . Enter different strings in first and second textbox.
On clicking the First command button, concatenation of two strings should be displayed in third text box and on clicking second
command button , reverse of string should display in third text box.
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ass5a3 extends JFrame implements ActionListener
{
String op;
String ans,ans1,rev;
JTextField t1,t2,t3;
JButton b1,b2;
JPanel p1,p2;
public ass5a3()
{
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);

b1=new JButton("Concatenation");
b2=new JButton("Reverse");

p1=new JPanel();
p1.setLayout(new GridLayout(3,1));
p1.add(t1);
p1.add(t2);
p1.add(t3);

p2=new JPanel();
p2.setLayout(new GridLayout(2,1));
p2.add(b1);
p2.add(b2);

setLayout(new GridLayout(2,1));
add(p1);
add(p2);

b1.addActionListener(this);
b2.addActionListener(this);

setBounds(100,100,500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{

JButton b=(JButton)ae.getSource();
String s1=t1.getText();
String s2=t2.getText();
if(b==b1)
{
ans=s1+s2;
t3.setText(ans);
}
else if(b==b2)
{
if(t3.getText()!="")
{
StringBuffer sb=new StringBuffer(ans);
sb.reverse();
t3.setText(sb.toString());
}
else{
ans1="STRING NOT AVAILABLE";
t3.setText(ans1);
}
}
}
public static void main(String[] args)
{
new ass5a3();
}
}

SET B:

a) Write a Java program to design a screen using Awt that will take a user name and password. If the user name and password are
not same, raise an Exception with appropriate message. User can have 3 login chances only. Use clear button to clear the
TextFields.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ass5b1 extends JFrame implements ActionListener{
static int n;
Panel p1,p2;
JLabel l1,l2;
JPasswordField p;
JTextField t;
Button b1,b2;
ass5b1()
{
p1=new Panel();
l1=new JLabel("User name");
l2=new JLabel("Password");

t=new JTextField(20);
p=new JPasswordField(10);
b1=new Button("Submit");
b2=new Button("Clear");
p1.setLayout(new GridLayout(2,1));
p1.add(l1);
p1.add(t);
p1.add(l2);
p1.add(p);

p2=new Panel();
p2.setLayout(new GridLayout(2,1));
p2.add(b1);
p2.add(b2);

b1.addActionListener(this);
b2.addActionListener(this);

setLayout(new GridLayout(2,1));
add(p1);
add(p2);
setSize(500,500);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
String s1=t.getText();
char c[]=new char[50];
c=p.getPassword();
String s2=new String(c);
if(s1.equals("mahebshaikh") && s2.equals("ms03"))
{
JOptionPane.showMessageDialog(null,"Login Succesfull");
n=0;
}
else
{
JOptionPane.showMessageDialog(null,"Login Failed");
t.setText("");
p.setText("");
n++;
if(n==3)
System.exit(0);
}
}
else if(e.getSource()==b2)
{
t.setText("");
p.setText("");
}
}
public static void main(String[] args)
{
new ass5b1();
}
}

b) Write a java program to create the following GUI for user registration form. Perform the following validations: i. Password
should be minimum 6 characters containing atleast one uppercase letter, one digit and one symbol. ii. Confirm password and
password fields should match. iii. The Captcha should generate two random 2 digit numbers and accept the sum from the user. If
above conditions are met, display “Registration Successful” otherwise “Registration Failed” after the user clicks the Submit
button.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ass5b2 extends JFrame implements ActionListener{
JPanel p1,p2;
JTextField t;
JPasswordField p;
JLabel l1,l2,info;
JButton b;
String cap;
int flag=0;
ass5b2()
{
p1=new JPanel();
p2=new JPanel();
t=new JTextField(20);
p=new JPasswordField(10);
b=new JButton("Register");
l1=new JLabel("Password");
l2=new JLabel("");
info=new JLabel("h1");
cap=generateCaptcha(4);
l2.setText("Captcha: "+cap);
p1.setLayout(new GridLayout(2,1));
p1.add(l1);
p1.add(p);
p1.add(l2);
p1.add(t);

p2.setLayout(new GridLayout(2,1));
p2.add(info);
p2.add(b);

setLayout(new GridLayout(2,1));
add(p1);
add(p2);
b.addActionListener(this);
setSize(400,400);
setVisible(true);
}
public boolean checkValidPassword(char[] password)
{
int u=0,l=0,d=0,sp=0;
if(password.length<6)
{
return false;
}
for(int i=0;i<password.length;i++)
{
char c=password[i];
if(Character.isUpperCase(c))
{
u=1;
}
else if(Character.isLowerCase(c))
{
l=1;
}
else if(Character.isDigit(c))
{
d=1;
}
if(!Character.isLetter(c) && !Character.isDigit(c) && !Character.isWhitespace(c))
{
sp=1;
}
}
if(u==1 && l==1 && sp==1 && d==1)
{
return true;
}
else
return false;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
String message="";
char[] password=p.getPassword();
if(checkValidPassword(password)==true)
{
message="Valid Password";
flag=1;
}
else
{
message="Invalid Password";
flag=0;
}
info.setText("");
info.setText(message);
if(checkCaptcha(cap,t.getText())==false)
{
info.setText("");
info.setText("Wrong Captcha!Try again.");
flag=0;
}
if(flag==1)
{
info.setText("");
info.setText("Registration Successful!");
}
else
{
info.setText("Registration Unsuccessful");
}
}
}
public boolean checkCaptcha(String cap,String t1)
{
String s1=t.getText();
if(cap.equals(s1))
return true;
else
return false;
}
public String generateCaptcha(int n)
{
cap="";
String a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
while(n-->0)
{
int index=(int)(Math.random()*62);
cap+=a.charAt(index);
}
return cap;
}
public static void main(String[] args)
{
new ass5b2();
}
}

c) Write a program to display the following menus and sub-menus.

import java.awt.event.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class Menu extends JFrame implements ActionListener
{
JMenu m1,m2;
JMenuBar mb;
JMenuItem i1,i2,i3,i4,i5,i6,i7;
JTextArea t;
JPanel p;
Menu()
{
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("File");
m2=new JMenu("Save As");

i1=new JMenuItem("New");
i2=new JMenuItem("Open");
i3=new JMenuItem("Save");
i4=new JMenuItem("ppt");
i5=new JMenuItem("doc");
i6=new JMenuItem("pdf");
i7=new JMenuItem("Exit");

t=new JTextArea("Text Area");

m1.add(i1);
m1.add(i2);
m1.add(i3);
m1.add(m2);
m1.addSeparator();
m1.add(i7);
m2.add(i4);
m2.add(i5);
m2.add(i6);

mb.add(m1);
setJMenuBar(mb);
p.setLayout(new BorderLayout());
p.add(t,BorderLayout.SOUTH);
add(p);

i2.addActionListener(this);

setTitle("MenuBar");
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==i2)
{
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION)
{
File f=fc.getSelectedFile();
String fpath=f.getPath();
try
{
BufferedReader br=new BufferedReader(new FileReader (fpath));
String s1="",s2="";
while((s1=br.readLine())!=null)
{
s2+=s1+"\n";
}
t.setText(s2);
}catch(Exception ev) {}

}
}
}
public static void main(String args[])
{
new Menu();
}

}
Filename: Java codes
Directory: C:\Users\Inara\OneDrive\Documents
Template: C:\Users\Inara\AppData\Roaming\Microsoft\Templates\Normal.dotm
Title:
Subject:
Author: Inara
Keywords:
Comments:
Creation Date: 10/27/2022 1:16:00 PM
Change Number: 9
Last Saved On: 10/27/2022 5:04:00 PM
Last Saved By: Inara
Total Editing Time: 47 Minutes
Last Printed On: 11/16/2022 11:48:00 AM
As of Last Complete Printing
Number of Pages: 33
Number of Words: 6,118 (approx.)
Number of Characters: 34,876 (approx.)

You might also like