Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 30

10 marks )

**************10MARKS
PROGRAM*************

***********************************************************************************
****************************************************************

Q1)Write a program to read the First Name and Last Name of a person, his weight and
height using command line arguments. Calculate the BMI Index which is defined as
the individual's body mass divided by the square of their height.
(Hint : BMI = Wts. In kgs / (ht)2)

public class BMICalculator {


public static void main(String[] args) {
String firstName = args[0];
String lastName = args[1];
double weight = Double.parseDouble(args[2]);
double height = Double.parseDouble(args[3]);
double bmiIndex = weight / (height * height);
System.out.println("Hello " + firstName + " " + lastName + " !");
System.out.println("Your BMI Index is: " + bmiIndex);
}
}

***********************************************************************************
****************************************************************
Q2) Write a program to accept ‘n’ name of cities from the user and sort them in
ascending order
Ans:
import java.util.Scanner;

class SortStrings
{
public static void main(String args[])
{
String temp;
Scanner SC = new Scanner(System.in);

System.out.print("Enter the value of N: ");


int N= SC.nextInt();
SC.nextLine(); //ignore next line character

String names[] = new String[N];

System.out.println("Enter names: ");


for(int i=0; i<N; i++)
{
System.out.print("Enter name [ " + (i+1) +" ]: ");
names[i] = SC.nextLine();
}

//sorting strings

for(int i=0; i<N; i++)


{
for(int j=1; j<N; j++)
{
if(names[j-1].compareTo(names[j])>0)
{
temp=names[j-1];
names[j-1]=names[j];
names[j]=temp;
}
}
}

System.out.println("\nSorted names are in Ascending Order: ");


for(int i=0;i<N;i++)
{
System.out.println(names[i]);
}
}
}

***********************************************************************************
****************************************************************

Q3) Write a Program to print all Prime numbers in an array of ‘n’ elements. (use
command line arguments)
import java.util.*;
class Prime{
public static void main(String args []){
int i,j=0;
boolean isPrime;
// int a[]=new int[args.length];
for(i=0;i<args.length;i++){
System.out.println(args[i]);
}
for(i=0;i<args.length;i++){
for(j=2;j<i;j++){
isPrime=true;
if(i%j==0){
isPrime=false;
break;
}
if(isPrime){
System.out.println(i+"are the prime number in array");
}
}
}
}
}

***********************************************************************************
****************************************************************

Q4) Write a program to print an array after changing the rows and columns of a
given two-dimensional array.
import java.util.*;
class TransArr{
public static void main(String args[]){
int r,c,i,j,t=0;
Scanner In=new Scanner(System.in);
System.out.print("Enter no of rows: ");
r=In.nextInt();
System.out.print("Enter no of column: ");
c=In.nextInt();
int a[][]=new int[r][c];
System.out.println("Enter "+r*c+" Elements: ");
for(i=0;i<r;i++){
for(j=0;j<c;j++){
a[i][j]=In.nextInt();
}
}
System.out.println("Array Representation: ");
for(i=0;i<r;i++){
for(j=0;j<c;j++){
System.out.print(a[i][j]+" ");
}
System.out.print("\n");
}
for(i=0;i<r;i++){
for(j=i+1;j<c;j++){
t=a[i][j];
a[i][j]=a[j][i];
a[j][i]=t;
}
}

System.out.println("Transpose Matrix: ");


for(i=0;i<r;i++){
for(j=0;j<c;j++){
System.out.print(a[i][j]+" ");
}
System.out.print("\n");

}
}
}

***********************************************************************************
****************************************************************

Q5) 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.
Ans:

import java.util.Scanner;

class Continent{
public static final Scanner IN=new Scanner(System.in);
String cont;
void con(){

System.out.println("Enter the continent name:");


cont=IN.nextLine();

}
}
class Country extends Continent{
String cou;
void cont(){

System.out.println("Enter the Country name:");


cou=IN.nextLine();

}
}
class State extends Country{
String st,pl;
void sta(){

System.out.println("Enter the State name:");


st=IN.nextLine();

System.out.println("Enter the place:");


pl=IN.nextLine();

}
}

class Display extends State{


void display(){

System.out.println("Continent is :"+cont);
System.out.println("Country is :"+cou);
System.out.println("State is :"+st);
System.out.println("Place is:"+pl);
}
}
class JavaPractical{
public static void main(String[] args) {
Display s=new Display();
s.con();
s.cont();
s.sta();
s.display();
}
}

***********************************************************************************
****************************************************************

Q6) Write a program to display the Employee(Empid, Empname, Empdesignation, Empsal)


information using toString().

class Employee
{
int id,salary;
String name;
String city;
Employee(int id,String name,int salary,String city)
{
this.id=id;
this.name=name;
this.salary=salary;
this.city=city;
}
public String toString()
{
return this.id+"\n"+this.name+"\n"+this.salary+"\n"+this.city;
}
public static void main(String args[])
{
Employee e1=new Employee(111,"rakesh",50000,"lucknow");

System.out.println("employee details"+e1);

}
}

***********************************************************************************
****************************************************************

Q7) Create a class Sphere, to calculate the volume and surface area of sphere.
(Hint : Surface area=4*3.14(r*r), Volume=(4/3)3.14(r*r*r))

class surfaceareaandvolume {
public static void main(String[] args)
{
double r = 5.0, surfacearea = 0.0, volume = 0.0;
surfacearea = 4 * 3.14 * (r * r);
volume = ((double)4 / 3) * 3.14 * (r * r * r);

System.out.println("surfacearea of sphere ="


+ surfacearea);

System.out.println("volume of sphere =" + volume);


}
}

***********************************************************************************
****************************************************************

Q8) Write a program to find the cube of given number using functional interface.

//cube
import java.util.Scanner;
public class Main
{
interface operation
{
public int cube();
}
static class number implements operation
{
int num;
number(int num)
{
this.num = num;
}
public int cube()
{
return (num * num * num);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter a number:");
int num = sc.nextInt();
number n1 = new number(num);
System.out.println("cube of " + num + " is " + n1.cube());
}
}

//number
import java.util.*;
public class Main
{
interface operation
{
public int cube();
}
static class number implements operation
{
int num;
number(int num)
{
this.num = num;
}
public int cube()
{
return (num * num * num);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter a number:");
int num = sc.nextInt();
number n1 = new number(num);
System.out.println("cube of " + num + " is " + n1.cube());
}
}

***********************************************************************************
****************************************************************
Q9) Define an interface “Operation” which has method 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 volume

import java.io.*;
import java.util.*;
interface Operation
{
float pi = 3.14f;
void area(float r, float h);
void volume(float r, float h);
}
class Cylinder implements Operation
{
public void area(float r, float h)
{
System.out.print("\nArea of the cylinder is: " + (2 * r * pi * (r + h)));
}
public void volume(float r, float h)
{
System.out.println("\n\nVolume of the cylinder is: " + (pi * r * r * h) + "\n");
}
}
class main1
{
public static void main(String args[])
{
int r, h;
Cylinder ob = new Cylinder();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius of the cylinder: ");
r = sc.nextInt();
System.out.print("Enter the height of the cylinder: ");
h = sc.nextInt();
ob.area(r, h);
ob.volume(r, h);
}
}

***********************************************************************************
****************************************************************

Q10) Write a program to accept a file name from command prompt, if the file exits
then display number of words and lines in that file.

import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WordCountInFile


{
public static void main(String[] args)
{
BufferedReader reader = null;
int wordCount = 0;

int lineCount = 0;

try
{
//Creating BufferedReader object

reader = new BufferedReader(new FileReader("sample.txt"));

//Reading the first line into currentLine

String currentLine = reader.readLine();

while (currentLine != null)


{

lineCount++;

String[] words = currentLine.split(" ");

wordCount = wordCount + words.length;

currentLine = reader.readLine();
}

System.out.println("Number Of Words In A File : "+wordCount);

System.out.println("Number Of Lines In A File : "+lineCount);


}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

***********************************************************************************
****************************************************************

Q11) Write a program to accept a number from the user, if number is zero then throw
user defined exception “Number is 0” otherwise check whether no is prime or not
(Use static keyword).

import java.io.*;
class zerono extends Exception
{
zerono(String msg)
{

super(msg);
}

}
class user1
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter number");
int n=Integer.parseInt(br.readLine());
if(n==0)
throw new zerono("number is zero");
else
{
int i=1,c=0;
while(i<=n)
{
if (n%i==0)
{
c++;
}
i++;
}
if(c==2)
System.out.println("given number is prime");
else
System.out.println("not prime");

}catch(zerono e)
{
System.out.println(e.getMessage());
}
}

}
***********************************************************************************
****************************************************************

Q12) Write a program to implement Border Layout Manager.

import java.awt.*;

import java.awt.event.*;
public class border extends Frame
{
Button b1,b2,b3,b4;
TextField t1;
Frame f;
public border()
{
f=new Frame();
f.setSize(250,250);
f.setVisible(true);
f.setLayout(new BorderLayout());
b1=new Button("B1");
b2=new Button("B2");
b3=new Button("B3");
b4=new Button("B1");
t1=new TextField(30);
f.add("North",b1);
f.add("South",b2);
f.add("East",b3);
f.add("West",b4);
f.add("Center",t1);

public static void main(String args[])


{
border t=new border();

}
}

***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************

***********************************************************************************
*********************************************************

****************10 MARKS PROGRAM END


HERE****************
***********************************************************************************
*********************************************************

***********************************************************************************
*********************************************************

***********************************************************************************
*********************************************************

***********************************************************************************
*********************************************************
*************20 MARKS PROGRAM*************

20 marks )
Q1) 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 cricket
{
static String name[]=new String[10],nm;
static int inngs[]=new int[10],notout[]=new int[10],runs[]=new int[10],r,in,n;
static double avg[]=new double[10],p;

void get(int i) throws IOException


{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
{
r=i+1;
System.out.println("Enter the details of "+r+" player:");
try
{
System.out.println("Enter the name:");
name[i]=br.readLine();
System.out.println("Enter the no of innings:");
inngs[i]=Integer.parseInt(br.readLine());
System.out.println("Enter the no of times not out:");
notout[i]=Integer.parseInt(br.readLine());
System.out.println("Enter the total runs:");
runs[i]=Integer.parseInt(br.readLine());
avg[i]=batavg(i);
}
catch(NumberFormatException e)
{
System.out.println("Invalid input");
}
}
}
static double batavg(int i)
{
p=inngs[i]+notout[i];
return(p);
}
static void show()
{
System.out.println(" The sorted list is on the basis of average: ");
System.out.println("Player_name No_of_innings No_of_times_Notout
Total_Runs Batting_average");
for(int i=0;i<n;i++)
System.out.println(name[i]+"\t\t"+inngs[i]+"\t\t"+notout[i]+"\t\t
"+runs[i]+"\t\t"+avg[i]);
}
static void sort()
{
for(int j=0;j<n;j++)
{
for(int i=j+1;i<n;i++)
{
if(avg[j] > avg[i])
{
p=avg[j];
avg[j]=avg[i];
avg[i]=p;
nm=name[j];
name[j]=name[i];
name[i]=nm;
r=notout[j];
notout[j]=notout[i];
notout[i]=r;
in=inngs[j];
inngs[j]=inngs[i];
inngs[i]=in;
r=runs[j];
runs[j]=runs[i];
runs[i]=r;

}
}
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
cricket[] c=new cricket[10];
System.out.println("Enter the how many cricket player details you want: ");
n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
c[i]=new cricket();
c[i].get(i);
}
sort();
show();
}
}

***********************************************************************************
*******************************
Q2) 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.

//package SY
package SY;
import java.io.*;
public class SYMarks

public int c,m,e;

public void get() throws Exception

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter computer total");

c = Integer.parseInt(br.readLine());

System.out.println("Enter maths total");

m = Integer.parseInt(br.readLine());

System.out.println("Enter electronic total");

e = Integer.parseInt(br.readLine());
}

public void put()

System.out.println("Computer total is: "+c);

System.out.println("Maths total is: "+m);

System.out.println("Electronic total is: "+e);

//package TY
package TY;
import java.io.*;
public class TYMarks

{
public int t,p;

public void get() throws Exception

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter theory marks");

t = Integer.parseInt(br.readLine());

System.out.println("Enter practical marks");

p=Integer.parseInt(br.readLine());

public void put()

System.out.println("Therory marks: "+t);

System.out.println("Practical marks: "+p);

//MAIN PROGRAM
import SY.*;
import TY.*;
import java.io.*;

class Student

int rno;

String name;

SYMarks s = new SYMarks();

TYMarks t = new TYMarks();

public void get() throws Exception

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter roll no: ");

rno = Integer.parseInt(br.readLine());

System.out.println("Enter name: ");

name = br.readLine();

s.get();

t.get();

public void put()

System.out.println("Roll no: "+rno);

System.out.println("Name: "+name);

s.put();

t.put();

void cal()throws Exception

int total,per;

total = s.c + t.t + t.p ;

System.out.println("Total is:"+total);

per = total/3;

if(per >= 70)

System.out.println("Grade:A");

else

if(per > 60 && per <= 70)

System.out.println("Grade:B");

else
if(per > 50 && per <= 60)

System.out.println("Grade:C");

else
if(per <= 40)

System.out.println("Grade:Fail");

class Slip20_1

public static void main(String arg[]) throws Exception

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter no of Students : ");

int n = Integer.parseInt(br.readLine());

Student s1[] = new Student[n];

for(int i=0;i<n;i++)

s1[i] = new Student();

s1[i].get();

s1[i].put();

s1[i].cal();

***********************************************************************************
****************************
Q3) Write a program to display the system date and time in various formats shown
below: 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

import java.text.SimpleDateFormat;
import java.util.*;
public class main2
{
public static void main(String[] args)
{
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate1 = formatter.format(date);
System.out.println("Current date is : " + strDate1);
formatter = new SimpleDateFormat("MM-dd-yyyy");
String strDate2 = formatter.format(date);
System.out.println("Current date is : " + strDate2);
formatter = new SimpleDateFormat("EEEE MMMM dd yyyy");
String strDate3 = formatter.format(date);
System.out.println("Current date is : " + strDate3);
formatter = new SimpleDateFormat("E MMMM dd HH:mm:ss z yyyy");
String strDate4 = formatter.format(date);
System.out.println("Current date and time is : " + strDate4);
formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a");
String strDate5 = formatter.format(date);
System.out.println("Current date and time is : " + strDate5);
formatter = new SimpleDateFormat("HH:mm:ss");
String strDate6 = formatter.format(date);
System.out.println("Current time is : " + strDate6);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
System.out.println("current week of year is : " +
calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("current week of month is : " +
calendar.get(Calendar.WEEK_OF_MONTH));
System.out.println("current day of the year is : " +
calendar.get(Calendar.DAY_OF_YEAR));
}
}
***********************************************************************************
***************************

Q4) Write a program to accept the username and password from user if username and
password are not same then raise "Invalid Password" with appropriate msg.

import java.util.*;

class invalidpass extends Exception {

invalidpass(String msg) {
super(msg);
}
}

class throw7 {

public static void main(String args[]) throws Exception {


try {
Scanner d = new Scanner(System.in);
System.out.println("Enter user name:");
String uname = d.nextLine();
System.out.println("Enter password:");
String pwd = d.nextLine();
if ((uname.equals(pwd)))
System.out.println( "user name is " + uname + " password is " + pwd); else
throw new invalidpass("invalid password");
} catch (invalidpass e) {
System.out.println(e.getMessage());
}
}
}

***********************************************************************************
*******************************
Q5) Write a program to create a package name student. Define class StudentInfo with
method to display information about student such as rollno, class, and percentage.
Create another class StudentPer with method to find percentage of the student.
Accept student details like rollno, name, class and marks of 6 subject from user.
Ans:
//Javac -d . Student. Java //package name
//Javac StudentMain.java //program name
//Java StudentMain

package mca;

public class Student {


public int r_no;
public String name;
public int a, b, c, d, e, f;
int sum = 0;

public Student(int roll, String nm, int m1, int m2, int m3, int m4, int m5, int
m6) {
r_no = roll;
name = nm;
a = m1;
b = m2;
c = m3;
d = m4;
e = m5;
f = m6;

sum = a + b + c + d + e + f;
}

public void display() {


System.out.println("Roll_no : " + r_no);
System.out.println("Name : " + name);
System.out.println("-----MARKS-------");
System.out.println("Java : " + a);
System.out.println("Webtech: " + b);
System.out.println("Python : " + c);
System.out.println("OS : " + d);
System.out.println("CN : " + e);
System.out.println("DS : " + f);
System.out.println("Total : " + sum);
System.out.println("percentage: " + sum / 6);
System.out.println("------------------");
}
}
import mca.Student;
import java.util.*;
import java.lang.*;
import java.io.*;

class StudentMain {
public static void main(String[] args) {
String nm;
int roll;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Roll no:= ");
roll = sc.nextInt();
System.out.print("Enter Name:= ");
nm = sc.next();
int m1, m2, m3, m4, m5, m6;
System.out.print("Enter 6 sub mark:= ");
m1 = sc.nextInt();
m2 = sc.nextInt();
m3 = sc.nextInt();
m4 = sc.nextInt();
m5 = sc.nextInt();
m6 = sc.nextInt();
Student s = new Student(roll, nm, m1, m2, m3, m4, m5, m6);
s.display();
}
}

***********************************************************************************
*******************************
Q6) Design a screen to handle the Mouse Events such as MOUSE_MOVED
and MOUSE_CLICKED and display the position of the Mouse_Click in a TextField.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;

public class Mouse extends Applet


implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{

addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);

}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="JAVA";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="PHP";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="TYBCS";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="GRAPHICS";
setBackground(Color.yellow);

repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="NETWORKING";
setBackground(Color.pink);
showStatus("Mouse Clicked"+m.getX()+" "+m.getY());

repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

***********************************************************************************
*******************************
Q7) Create an abstract class “order” having members id, description. Create two
subclasses “PurchaseOrder” and “Sales Order” having members customer name and
Vendor name respectively. Definemethods accept and display in all cases. Create 3
objects each of Purchase Order and Sales Order and accept and display details.

import java.io.*;
import java.util.*;

abstract class order


{
int id;
String desc;
public order(int x,String y)
{
id=x;
desc=y;
}

abstract void display();


}
class Salesorder extends order
{
String cname;
String vname;

public Salesorder(int a,String b,String c,String d)


{
super(a,b);
cname=c;
vname=d;
}
void display()
{
System.out.println(id+"\t "+desc+"\t\t"+cname+"\t\t"+vname);
}
}
class Purchaseorder extends order
{
String cname;
String vname;
public Purchaseorder(int p,String q,String r,String s)
{
super(p,q);
cname=r;
vname=s;
}
void display()
{
System.out.println(id+"\t "+desc+"\t\t"+cname+"\t\t"+vname);
}
}
class test11
{
public static void main(String args[]) throws Exception
{

int i;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many objects:");
int n=s.nextInt();
Salesorder[] f=new Salesorder[n];
Purchaseorder[] f1=new Purchaseorder[n];
System.out.println("Enter type of order:");
String ch=s.next();
if(ch.equals("Salesorder"))
{
for(i=0;i<n;i++)
{
System.out.println("Enter id:");
int a=s.nextInt();
System.out.println("Enter desc:");
String b=s.next();
System.out.println("Enter customer name:");
String c=s.next();
System.out.println("Enter vendor name:");
String d=s.next();

f[i]=new Salesorder(a,b,c,d);
}
System.out.println("id \t desc \t cname \t vname ");
for(i=0;i<n;i++)
f[i].display();
}
else
{
for(i=0;i<n;i++)
{
System.out.println("Enter id:");
int a1=s.nextInt();
System.out.println("Enter desc:");
String b1=s.next();
System.out.println("Enter customer name:");
String c1=s.next();
System.out.println("Enter vendor name:");
String d1=s.next();
f1[i]=new Purchaseorder(a1,b1,c1,d1);
}
System.out.println("id \t desc \t cname \t vname ");
for(i=0;i<n;i++)
f1[i].display();
}
}
}

***********************************************************************************
*******************************

Q8) Write a 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.
Ans:
import java.awt.*;
import java.awt.event.*;
class InvalidPasswordException extends Exception
{
InvalidPasswordException()
{
System.out.println(" User name and Password is not same");
}
}
public class PasswordDemo extends Frame implements ActionListener
{
Label uname,upass;
TextField nametext;
TextField passtext,msg;
Button login,Clear;
Panel p;
int attempt=0;
char c='*';

public void login()


{
p=new Panel();
uname=new Label("Use Name: " ,Label.CENTER);
upass=new Label ("Password: ",Label.RIGHT);

nametext=new TextField(20);
passtext =new TextField(20);
passtext.setEchoChar(c);
msg=new TextField(10);
msg.setEditable(false);

login=new Button("Login");
Clear=new Button("Clear");
login.addActionListener(this);
Clear.addActionListener(this);

p.add(uname);
p.add(nametext);
p.add(upass);
p.add(passtext);
p.add(login);
p.add(Clear);
p.add(msg);
add(p);

setTitle("Login ");
setSize(290,200);
setResizable(false);
setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
Button btn=(Button)(ae.getSource());
if(attempt<3)
{
if((btn.getLabel())=="Clear")
{
nametext.setText("");
passtext.setText("");
}
if((btn.getLabel()).equals("Login"))
{
try
{
String user=nametext.getText();
String upass=passtext.getText();

if(user.compareTo(upass)==0)
{
msg.setText("Valid");
System.out.println("Username is valid");
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e)
{
msg.setText("Error");
}
attempt++;
}
}
else
{
System.out.println("you are using 3 attempt");
System.exit(0);
}
}
public static void main(String args[])
{
PasswordDemo pd=new PasswordDemo();
pd.login();
}
}

***********************************************************************************
*******************************
Q9) 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.

Ans:import java.io.*;
import java.util.*;

abstract class staff {


int id;
String name;

public staff(int x, String y) {


id = x;
name = y;
}

abstract void display();


}

class officestaff extends staff {


String dep;

public officestaff(int a, String b, String c) {


super(a, b);
dep = c;
}

void display() {
System.out.println(id + "\t " + name + "\t\t" + dep);
}
}

class test {

public static void main(String args[]) throws Exception {


int i;
Scanner s = new Scanner(System.in);
System.out.println("Enter how many objects:");
int n = s.nextInt();
officestaff[] f = new officestaff[n];
for (i = 0; i < n; i++) {
System.out.println("Enter id:");
int a = s.nextInt();
System.out.println("Enter name:");
String b = s.next();
System.out.println("Enter department:");
String c = s.next();

f[i] = new officestaff(a, b, c);


}
System.out.println("id \t Name \t Depart");
for (i = 0; i < n; i++) f[i].display();
}
}

***********************************************************************************
*******************************
Q10)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.
Ans:
import java.util.*;
class Patient1
{
String name;
int age;
int oxylevel;
int HRCTreport;
Patient1(String name, int age, int oxylevel, int HRCTreport)
{
this.name = name;
this.age = age;
this.oxylevel = oxylevel;
this.HRCTreport = HRCTreport;
}
}
public class petient1 extends Exception
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("How many patient you want insert:");
int number = sc.nextInt();
Patient1[] ob = new Patient1[number];
for(int j=0; j<number; j++)
{
System.out.println("Enter Name ");
String name = sc.next();
System.out.println("Enter Age ");
int age = sc.nextInt();
System.out.println("Enter oxygen level");
int oxylevel = sc.nextInt();
System.out.println("Enter HRCT report");
int HRCTreport = sc.nextInt();
ob[j] = new Patient1(name, age, oxylevel, HRCTreport);
}

for(int j=0; j<number; j++)


{
if(ob[j].oxylevel < 95 && ob[j].HRCTreport > 10)
try
{
throw new NullPointerException("not positive \n");
}
catch(Exception e)
{
System.out.println("Patient is Covid Positive(+) and Need to
Hospitalized\n");

}
else
{
System.out.println("name: "+ob[j].name);
System.out.println("age " + ob[j].age);
System.out.println("oxygen level " +ob[j].oxylevel);
System.out.println("HRCT report " + ob[j].HRCTreport);
System.out.println("\n");
}
}
}
}

***********************************************************************************
*******************************
Q11)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.
Ans:
import java.io.*;
import java.util.*;
class Cricket {
String name;
int inning, tofnotout, totalruns;
float batavg;
public Cricket(){
name=null;
inning=0;
tofnotout=0;
totalruns=0;
batavg=0;
}
public void get() throws IOException{
Scanner br=new Scanner(System.in);
System.out.println("Enter the name, no of innings, no of times not out,
total runs: ");
name=br.nextLine();
inning=Integer.parseInt(br.nextLine());
tofnotout=Integer.parseInt(br.nextLine());
totalruns=Integer.parseInt(br.nextLine());
}
public void put(){
System.out.println("Name="+name);
System.out.println("no of innings="+inning);
System.out.println("no times notout="+tofnotout);
System.out.println("total runs="+totalruns);
System.out.println("bat avg="+batavg);
}
static void avg(int n, Cricket c[]){
try{
for(int i=0;i<n;i++){
c[i].batavg=c[i].totalruns/c[i].inning;
}
}catch(ArithmeticException e){
System.out.println("Invalid arg");

}
}
static void sort(int n, Cricket c[]){
String temp1;
int temp2,temp3,temp4;
float temp5;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(c[i].batavg<c[j].batavg){
temp1=c[i].name;
c[i].name=c[j].name;
c[j].name=temp1;
temp2=c[i].inning;
c[i].inning=c[j].inning;
c[j].inning=temp2;
temp3=c[i].tofnotout;
c[i].tofnotout=c[j].tofnotout;
c[j].tofnotout=temp3;
temp4=c[i].totalruns;
c[i].totalruns=c[j].totalruns;
c[j].totalruns=temp4;
temp5=c[i].batavg;
c[i].batavg=c[j].batavg;
c[j].batavg=temp5;
}
}
}
}
}
public class a4sa1 {
public static void main(String args[])throws IOException{
Scanner br=new Scanner(System.in);
System.out.println("Enter the limit:");
int n=Integer.parseInt(br.nextLine());
Cricket c[]=new Cricket[n];
for(int i=0;i<n;i++){
c[i]=new Cricket();
c[i].get();
}
Cricket.avg(n,c);
Cricket.sort(n, c);
for(int i=0;i<n;i++){
c[i].put();
}
}

***********************************************************************************
*******************************
Q12) Write a menu driven program to perform the following operations on
multidimensional array ie matrices :
 Addition
 Multiplication
 Exit
import java.util.*;

class Operation {

void addarry() {
Scanner IN = new Scanner(System.in);
int r1, c1, r2, c2;

System.out.println("Enter the no.of row in a arry:");


r1 = IN.nextInt();
System.out.println("Enter the no.of coloumn in a arry:");
c1 = IN.nextInt();
int a[][] = new int[r1][c1];
System.out.println("Enter the no.of row in b arry:");
r2 = IN.nextInt();
System.out.println("Enter the no.of coloumn in b arry:");
c2 = IN.nextInt();

System.out.println("Enter the elemnt in arry a");


for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
a[i][j] = IN.nextInt();
}
}
int b[][] = new int[a.length][a.length];
System.out.println("Enter the elemnt in arry b");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
b[i][j] = IN.nextInt();
}
}
// System.out.println("You enter matrix a is:");
// for (int i = 0; i < r1; i++) {
// for (int j = 0; j < c1; j++) {
// System.out.print(a[i][j] + " ");
// }
// System.out.println();
// }

// System.out.println("You enter matrix b is:");


// for (int i = 0; i < r1; i++) {
// for (int j = 0; j < c1; j++) {
// System.out.print(a[i][j] + " ");
// }
// System.out.println();
// }

int c[][] = new int[a.length][a.length];


for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("Addition of matrix is:");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}

void multarry() {
Scanner IN = new Scanner(System.in);
int r1, c1, r2, c2, i, j, k;

System.out.println("Enter the no.of row in a arry:");


r1 = IN.nextInt();
System.out.println("Enter the no.of coloumn in a arry:");
c1 = IN.nextInt();
int a[][] = new int[r1][c1];
System.out.println("Enter the no.of row in b arry:");
r2 = IN.nextInt();
System.out.println("Enter the no.of coloumn in b arry:");
c2 = IN.nextInt();

System.out.println("Enter the elemnt in arry a");


for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
a[i][j] = IN.nextInt();
}
}
int b[][] = new int[a.length][a.length];
System.out.println("Enter the elemnt in arry b");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
b[i][j] = IN.nextInt();
}
}
int d[][] = new int[a.length][a.length];
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
int s = 0;
for (k = 0; k < r1; k++) {
s = a[i][k] * b[k][j] + s;
}
d[i][j] = s;
}
}
System.out.println("Multiplication is:");
for ( i = 0; i < r1; i++) {
for ( j = 0; j < c1; j++) {
System.out.print(d[i][j] + " ");
}
System.out.println();
}
}
}

class ArrayPractical {
public static void main(String[] args) {

Scanner In = new Scanner(System.in);


int i, ch;
Operation a = new Operation();

do {
System.out.println("Press 1 for addition :");

System.out.println("Press 2 for Multiplication :");


System.out.println("Press 3 for Exit :");
ch = In.nextInt();

switch (ch) {
case 1:
a.addarry();
break;

case 2:
a.multarry();
break;

case 3:
System.exit(0);
break;

default:
System.out.println("Invalid choice!!!");

}
System.out.print("Press 1 for continue:");
i = In.nextInt();
} while (i == 1);

}
}

***************************************************END 20 MARKS
PROGRAM*********************************************************

You might also like