Вы находитесь на странице: 1из 37

OOPs Lab Solution Document

OOPS LAB - 1

1) You were given two problems by the teacher to be solved. (Use overloaded methods) a) There are ‘m’ students registered in the class with a capacity of ‘n’ seats. Your goal is to find out the number of ways students can be seated assuming there is no deficiency with the seats. b) You are supposed to calculate the area of a polygon based on number of inputs given by the user. Polygon can be a square, a rectangle or a scalene triangle. [LO - 1,2]

Solution :

a)

import java.io.*;

import java.math.*;

import java.util.*;

class Main

{

public static int fact(int num)

{

int f=1;

if(num==0)

return 1;

else

return num*fact(num-1);

}

public static void main(String[] args)

{

int std_count = 4;

int seat_fact=fact(n);

int std_seat_fact=fact(n-m);

float cal=(seat_fact/std_seat_fact);

System.out.println("the number of ways are"+cal);

}

b)

}

import java.util.*;

public class Main

{

public static double Calc_area(double a)

 { double area=a*a; return area; }

public static double Calc_area(double a,double b)

 { double area=a*b; return area; }

public static double Calc_area(double a,double b,double c)

 { double s=(a+b+c)/2; double area=Math.sqrt(s*(s-a)*(s-b)*(s-c)); return area; }

public static void main(String[] args)

{

double area,n1=5,n2=3,n3=3;

area=Calc_area(n1);

System.out.println("Area of the Square is:"+area);

area=Calc_area(n1,n2);

System.out.println("Area of the Rectangle is:"+area);

area=Calc_area(n1,n2,n3);

System.out.println("Area of the Scalene Triangle is:"+area);

}

}

2) Tony is appointed as a billing administrator in a Restaurant. According to the norms of the new government, GST and maintenance charges are to be displayed on the bill. Restaurant also offers a discount to their loyal customers of 10% if the bill is greater than 1000 rupees, else 5% for all other bills. Help him to calculate the total bill while displaying all the components separately. [LO - 4]

Solution :

import java.io.*;

import java.math.*;

import java.util.*;

import java.lang.*;

class Main

{

public static void main(String[] args)

{

float amount=1000,gst=5,main_tax=4,total_tax,dis_amount=0,total_bill,dis_per;

if(amount >=1000)

dis_per=10;

else

dis_per=5;

total_tax=((gst+main_tax)/100)*amount;

dis_amount=(dis_per/100)*amount;

total_bill=amount+total_tax-dis_amount;

}

}

3)A microbiologist wants to calculate the remaining amount of the bacteria after 5 minutes. Initially, there are ‘n’ number of bacteria. After her analysis on the given bacteria, she finds the decreasing rate of bacteria to be 0.0028 per minute. She approaches you, considering you to solve it through your java program. [LO - 4]

Solution :

import java.util.*;

class Main

{

public static void main(String[] args)

{

int count=5;

double init_bact=32.8;

while(count>=0)

 { init_bact-=(0.0028*init_bact); count--; }

System.out.println("The remaining Bacteria is:"+init_bact);

}

}

4)A Software is being developed by the management that displays SGPA of your current

semester. You are given the task to develop a module that calculates the SGPA with respect to the secured grade points corresponding to given number of credits in each subject. The credits for the courses are:

Graphics: 2, MVC: 4, COA: 3, Chemistry: 3, English: 2, Technical Skills: 1.5, Data Structures: 4

Complete your Module by displaying the SGPA of current semester.[LO - 3]

Solution :

import java.io.*;

import java.math.*;

import java.text.*;

import java.util.*;

import java.lang.*;

class Main

{

public static void main(String[] args)

{

int gph_g=10,mvc_g=9,coa_g=10,chem_g=10,eng_g=10,ts_g=9,ds_g=8;

double gph_c=2,mvc_c=4,coa_c=3,chem_c=3,eng_c=2,ts_c=1.5,ds_c=4;

Double SGPA = ((gph_g*gph_c) +(mvc_g*mvc_c)+ (coa_g*coa_c)+(chem_g*chem_c) +

(eng_g*eng_c) +(ts_g*ts_c)+(ds_g*ds_c))/19.5;

System.out.printf("your SGPA for the semester is %.2f:",SGPA);

}

}

5) You are appointed as a programmer of a newly taken up project for Bank-Customer

transactions of a National Bank. The management of the bank requires the customer to give out their name, account number, and the initial amount present in their account. The customer will request for the deposit and withdraw of amount from their account. Your program should be able to check whether the request can be accepted depending on the account balance in their account and display the appropriate message for their transaction while also displaying the remaining balance in his/her account. Make sure your program ensures the access of account number only to the account holder and the bank (Use two different classes for deposit and withdrawal). [LO - 1,3]

Solution :

class Deposit

{

public float deposit(float current,float amount)

{

current +=amount;

System.out.println("Amount deposited Successfully!!!");

return current;

}

}

class Withdrawal

{

public float withdrawal(float current,float amount)

{

if(amount>current)

System.out.println("Insufficient balance");

else

current-=amount;

System.out.println("Amount drawn successfully!!!");

return current;

}

}

class Bank

{

public static void main(String[] args)

{

float current=20000;

System.out.println("Current Balance is:"+current);

Deposit d=new Deposit();

current=d.deposit(current,20000);

System.out.println("Amount after deposit has done:"+current);

Withdrawal wd=new Withdrawal();

current=wd.withdrawal(current,1000);

System.out.println("Amount after withdrawal has done:"+current);

}

}

6) An IT Industry recruited a few employees and wants to maintain a record of their details containing their name,age and salary. You have been given the task to write a program to display the details, mentioning the salary to be hidden to others except that particular employee and the management. [LO - 5]

Solution :

class Employee

{

private int salary=5000;// It is visible in Employee class only

public int age=32;

public void displayDetail()

{

System.out.println("Employee salary :" + salary);

}

}

public class Main

{

public static void main(String args[])

{

String empName="rahul";

System.out.println("Employee name: "+empName);

Employee empObj = new Employee();

empObj.displayDetail();

System.out.println("Employee age: " + empObj.age);

}

}

OOPS LAB-2

1)

Ramesh’s house is located at a junction from which the places of his four friends are located at two coordinate points each. He must be at either one of their houses at the same time. Help him choose which house to go to by finding out the one with the nearest distance from his place. The coordinates of their houses are as follows:

[LO:1,3]

 Name Coordinates Ramesh (3,2) Friend A (2,3) Friend B (0,0) Friend C (5,8)

Friend D

(1,4)

Solution:

import java.lang.*;

import java.lang.Math;

class Nexthouse

{

public static void main(String args[])

 { int rx=3,ry=2; int x[]=new int[]{2,0,5,1}; int y[]=new int[]{3,0,8,4}; int ind=0; double s,max=100; for(int i=0;i<4;i++) { s=Math.sqrt(Math.pow((rx-x[i]),2)+Math.pow((ry-y[i]),2)); System.out.println("Distance to Friend"+(i+1)+" house is "+s); if(s

}

2)

Pavan and Praveen are playing rock - paper - scissor. Here rock = 0, paper = 1, scissor = 2. Their throws are as follows:

[LO:1,3]

 Rounds Round Round Round Round Round Round Round Round Round Round 1 2 3 4 5 6 7 8 9 10
 Pavan 0 1 1 2 0 0 1 2 1 0 Praveen 1 2 0 1 0 2 0 1 1 2

Compare and print the score of each of the player at the end of ten rounds and declare the winner.

Solution:

class Game

{

public static void main(String args[])

 { int a[]=new int[]{0,1,1,2,0,0,1,2,1,0}; int b[]=new int[]{1,2,0,1,0,2,0,1,1,2}; winner(a,b); }

static void winner(int a[],int b[])

{

int pavan=0,praveen=0;

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

{

if(a[i]==1 && b[i]==0)

pavan++;

else if(a[i]==0 && b[i]==2)

pavan++;

else if(a[i]==1 && b[i]==2)

pavan++;

else if(b[i]==1 && a[i]==0)

praveen++;

else if(b[i]==0 && a[i]==2)

praveen++;

else if(b[i]==1 && a[i]==2)

praveen++;

else if(a[i]==b[i])

}

continue;

if(pavan>praveen)

System.out.println("Pavan is the winner\n");

else if(praveen>pavan)

System.out.println("Praveen is the winner\n");

else(praveen==pavan)

System.out.println("There is a tie between Pavan and Praveen\n");

3)

}

}

The Government adopts the orphans of various age groups and sends them to an orphanage. Since the warden doesn’t know the exact count of the orphans help him by writing a program to count the total number of orphans and find the frequency of

similar age groups. (Use command line arguments as user input).

[LO:1,2]

Solution:

import java.util.*;

class Orphanage

{

public static void main(String[] args)

{

int cnt,val,ocnt=0;

int[] fre=new int[args.length]; for(int i=0;i<args.length;i++)

{

fre[i]=-1;

ocnt++;

}

System.out.println("The total no of orphans into the orphanage are: "+ocnt);

for(int i=0;i<args.length;i++)

{

cnt=1;

for(int j=i+1;j<args.length;j++)

{

if(args[i].equals(args[j]))

{

cnt++;

}

}

if(fre[i]!=0)

{

fre[j]=0;

}

fre[i]=cnt;

}

for(int i=0;i<args.length;i++)

{

if(fre[i]!=0)

{

System.out.println("The orphans with age "+args[i]+" are :

"+fre[i]);

}

}

}

}

4)

and found

Captain Jack Sparrow went for a treasure hunt with his crew. He came to an Island

five caves in a series numbered as (2, 5, 7, 4, 9). Help Captain Sparrow to

(1) Find the caves with treasure?

Hint: -G = (cave number+3) ^2 %10

If (G < 5) -> Cave has treasure.

(2) Find the caves with a new Treasure Map?

Hint: -M = |10 - cave number|%3

If (M==0) ->Cave has treasure map.

[LO:1,3]

Solution:

import java.lang.*;

import java.lang.Math; class Cave

{

public static void main(String args[])

 { int caves[]=new int[]{2,5,7,4,9}; treasure(caves,5); treasuremap(caves,5); }

public static void treasure(int caves[],int n)

{

int i,g;

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

{

g=(int)Math.pow((caves[i]+3),2)%10;

if(g<5)

System.out.println("Cave "+(i+1)+" has treasure");

}

}

public static void treasuremap(int caves[],int n)

{

int i,g;

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

{

g=Math.abs(10-caves[i])%10;

if(g<5)

System.out.println("Cave "+(i+1)+" has new treasure map");

}

}

}

5) Tom and Jerry found two bags of apples. The bag that Jerry chose contains 5 apples and the bag chosen by Tom has 3 apples. Tom wants to have more apples, so he swaps the bags. Write a program to display the apples in the two bags before and after swapping.

[LO:4]

Hint:-(Try using call by value and call by reference; Write which can be used to swap)

Solution:

public class callbyref

{

int x;

int y;

public static void main(String[] args)

 { callbyref obj =new callbyref(); obj.x=10; obj.y=20; System.out.println("Before swapping"); System.out.println("The val of x : "+obj.x); System.out.println("The val of y : "+obj.y); obj.swap(obj); System.out.println("After swapping"); System.out.println("The val of x : "+obj.x); System.out.println("The val of y : "+obj.y); }

public void swap(callbyref t) //t=OBJ

{

int temp=t.x;

}

}

t.x=t.y;

t.y=temp;

6) A Person had gone on a holiday. He decided to use his savings amount of 500\$. He allotted certain amount of money as his budget. During the holiday, he first goes on a safari ride which costs him about \$30. Then he goes out for lunch which costs him about \$40. Later, he finishes the day off by going for a movie which costs him \$15. Help him find out the amount left by the end of the holiday.

[LO:3,4]

(Every activity is a method in the class. Only initializing amount is called by value)

Solution:

import java.lang.*;

class Amountleft

{

int total;

public static void main(String args[])

 { Amountleft a=new Amountleft(); a.total=500; safari(a); lunch(a); movie(a); System.out.println("Remaining amount is "+a.total); }

static void safari(Amountleft a)

{

a.total=a.total-30;

}

static void lunch(Amountleft a)

{

a.total=a.total-40;

}

static void movie(Amountleft a)

}

{

}

a.total=a.total-15;

7) Write a program to help Alex find out the date and time. Solution:

import java.util.Date; public class Current

{

public static void main(String args[])

{

Date date = new Date(); System.out.println(date.toString());

}

}

[LO:4]

OOPS LAB-3

1)

Rakesh is participating in a Hackathon and it requires him to make a Login page. Help him out by writing a program to create the page. It should look as follows: [L.O 4]

Solution:

{

public static void main(String args[])

}

 2) A Mathematics faculty in class started asking questions about finding out the square root of a given number. He now put up a challenge to Satya to tell all the numbers starting from 1 to the given number (say n). Write a program to help him find out the square root of all those numbers: [ L.O 1] Solution: import java.util.*; class SquareRootDemo { public static void main(String[] args) { double n; int i; Scanner sc = new Scanner(System.in); n = sc.nextDouble(); for(i=1;i<=n;i++) { double squareRoot = Math.sqrt(i); System.out.println("number : "+i+":Square root:"+squareRoot); } } } 3) You have a file which contains confidential data in it. You want to send that data to one of your executives, but you need to send a duplicate copy. Copy the data from original file to duplicate file and send it: [ L.O 4]

Solution:

import java.io.*;

public class CopyFile

{

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

{

FileInputStream in = null;

FileOutputStream out = null; try

{

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1)

{

out.write(c);

}

}

finally

{

if (in != null)

4)

}

}

{

in.close();

}

if (out != null)

{

out.close();

}

}

While on his duty, a traffic police had the task of checking the speed of vehicles. It is given that if the speed is above 90kmph, there should be a fine of 1000/- imposed on the vehicle. Help him out by creating a program to for imposing of the fine. (Create two classes for police and speed check. All methods must be static): [ L.O 2,3] Solution:

import java.io.*;

import java.util.*;

class Police

{

public static void Police1(String id,int r)

{

System.out.println("vechical id number :"+id);

if(r==1)

System.out.println("fine imposed Rs 1000/-");

else System.out.println("No fine imposed");

}

}

class Fine

 { public static int Fine1(int speed) { if(speed>90) return 1; else return 0; } } public class Lab {

public static void main(String[] args)

{

Scanner sc=new Scanner(System.in); System.out.println("Enter car id : "); String id=sc.next(); System.out.println("Enter speed of vehicle :");

int speed=sc.nextInt(); int r=Fine.Fine1(speed);

Police.Police1(id,r);

}

}

 5) Full moon occurs for every 29.52 days. The last full moon occurred on August 14 th ,2019. Calculate next two full moon days without creating object of the class and calculate two previous full moon days by creating object of the class: [ L.O 3] Solution: import java.util.*; class NextFullMoons { static void nextFullMoons(String mon,int date) { date+=29.52-30; System.out.println("The First Next full moon after August 14th 2019 will be on: "+"September"+date+"th,2019"); date+=29.52-31; System.out.println("The Second Next full moon after August 14th 2019 will be on: "+"October"+date+"th,2019"); } } class PreviousFullMoons { void previousFullMoons(String mon,int date) { date-=29.52-31; System.out.println("The First Previous full moon before August 14th 2019 will be on: "+"July"+date+"th,2019"); date-=29.52-30; System.out.println("The Second Previous full moon before August 14th 2019 will be on: "+"June"+date+"th,2019"); } } public class Fullmoon { public static void main(String[] args) { PreviousFullMoons pfm=new PreviousFullMoons(); pfm.previousFullMoons("August",14); NextFullMoons.nextFullMoons("August",14); } } 6) Alex was asked to predict number of words and lines in a file. He was just given the file name. Help Alex to predict, Use Jframes to solve it: [ L.O 4] (Hint: Take Filename as input in the text field and print the Output in the separate text fields.)

Sample Output:

Solution:

import javax.swing.*;

import java.awt.event.*; import java.awt.*; import java.io.*; class NumberOfWords

{

public static String check(String s,char ch)

 { int count=0; try { FileInputStream fis=new FileInputStream(s); int d; while((d=fis.read())!=-1) { if((char)d==ch) count+=1; } } catch(Exception e) { return("File Not Found"); } String t=Integer.toString(count+1); return t; }

public static void main(String args[])

{

JFrame f=new JFrame("Creativity"); f.setVisible(true);

f.setSize(400,300);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p=new JPanel(); TextField tf=new TextField(20); TextField tf1=new TextField(20); TextField tf2=new TextField(20); JLabel l1=new JLabel("Number of words "); JLabel l2=new JLabel("Number of lines ");

JButton b1=new JButton("Submit");

{

public void actionPerformed(ActionEvent e)

}

}

7) You are working in DELL company. You’ve been asked to develop a program for the service center website of the company. It should contain Purchasing and Servicing options (Consider them as classes). Purchase class contains purchaseInspiron and purchaseAlienware methods, Service class contains serviceOfLaptop and serviceOfPc methods. Both service and purchase classes are in class Dell. (Use Inner Classes) [L.O

5]

Solution:

import java.util.*; class Dell{ class Purchase{ void vostra(){

System.out.println("Cost of the Vostra Product is \$ 200");

}

void alienware(){

System.out.println("Cost of the Alienware Product is \$ 450");

}

}

class Service{ void pc(){ System.out.println("Your PC will be serviced soon"); System.out.println("Thank You for using our service");

}

void laptop(){

System.out.println("Your LapTop will be serviced soon"); System.out.println("Thank You for using our service");

}

}

}

class Coustmer extends Dell{ public static void main(String args[]){ Scanner l = new Scanner(System.in); System.out.println("Welcome to Dell Help Center");

System.out.println("1.Prchase\n2.Service");

switch(choice){

case 1:

Coustmer.Purchase p = new Coustmer().new Purchase();

System.out.println("1.Vostra\n2.Alienware");

int select = l.nextInt(); System.out.println("Select the Product"); switch(select){ case 1: p.vostra(); System.out.println("Thank you for prchasing"); break; case 2: p.alienware(); System.out.println("Thank you for prchasing"); break;

}

break; case 2: Coustmer.Service q = new Coustmer().new Service();

System.out.println("1.PC\n2.LapTop");

int see = l.nextInt(); System.out.println("Select the Service"); switch(see){ case 1: q.pc(); break; case 2: q.laptop(); break;

}

}

break;

}

}

OOPS LAB - 4

1. A lottery shop owner is running two deals for his customers. In the first deal, he gives out one token at a cost of 5/- and in the second deal he gives out two tokens at a cost of 10/-. Each token value ranges from 0 to 5. Each customer gets one chance of playing the game of BIG SIX WHEEL. If he gets a value which is less than or equal to the token value, he wins a prize. Help him out by writing a program for this. (Use constructor overloading) [ L.O 1]

Solution:

import java.util.*;

class Lottery

{

int token_value1,token_value2;

Lottery()

{

System.out.println("Zero Parameterised Constructor");

}

Lottery(int tv)

{

token_value1=tv;

System.out.println("Token_value is: "+token_value1);

token_value2=0;

}

Lottery(int tv1, int tv2)

{

token_value1=tv1;

token_value2=tv2;

}

int check()

{

Random rand=new Random();

int flag=0;

int check=rand.nextInt(6);

System.out.println("Token_value 1 is: "+token_value1);

System.out.println("Token_value 2 is: "+token_value2);

System.out.println("The Big Six Wheel Score is: "+check);

if(token_value1 >= check || token_value2 >= check)

}

{

}

Else

{

}

flag=1;

flag=0;

if(flag==1)

{

return 1;

}

Else

{

return 0;

}

public static void main(String[] args)

{

Scanner sc=new Scanner(System.in);

System.out.println("Lottery House Offfers you 2 deals ");

System.out.println("1. One token for 5 Rupees/-");

System.out.println("2. Two token for 10 Rupees/-");

int choice=sc.nextInt();

Lottery b;

Lottery c;

int result=-1;

Random r=new Random();

 switch(choice) { case 1: b=new Lottery(r.nextInt(6)); result=b.check(); break; case 2: c=new Lottery(r.nextInt(6),r.nextInt(6)); result=c.check(); break; default: System.out.println("No offers available other than 5 and 10 Rupees"); }

/*Lottery b=new Lottery(2);

int result=b.check();*/

if(result == 1)

System.out.println("Kid, you've won the Lottery trial");

else

System.out.println("Kid you lost the Lottery trial, BETTER LUCK NEXTIME");

}

}

2. A customer of a bank wants to withdraw/deposit money from his account. There are 3 ATMs in his town. Help him out by writing a program such that his balance will be updated after a transaction in any of the ATMs. (Use ‘Account’ as Singleton Class and it should be Early Instantiated) [L.O 2]

Solution:

class Atm

 { private static Atm acc=null; public double Balance=123516; public static Atm amount() { if(acc==null) acc=new Atm(); return acc; } public void getAmount(int m) { if(Balance==0) System.out.println("Insufficient Balance"); else if(Balance-m<0) System.out.println("Insufficient Balance"); else Balance=Balance-m; } }

public class HelloWorld

{

public static void main(String args[])

{

Atm x=Atm.amount();

x.getAmount(10);

System.out.println(x.Balance);

Atm y = Atm.amount();

y.getAmount(1000);

System.out.println(y.Balance);

}

}

3. A Net Cafe has one printer and four systems which has a total of 100 papers. Write a program such that after every print command the number of papers left should be displayed on every system. Use GUI, consider each frame as a system. (Use Singleton class) [L.O 2]

Solution:

import java.util.*;

class Singleton

{

private int counter=100;

private static Singleton obj=null;

private Singleton()

{

System.out.println("\t object is created");

}

public static Singleton getInstance()

{

if(obj==null)

obj=new Singleton();

return obj;

}

public void used()

{

System.out.println("A paper is used");

this.counter-=1;

obj.remaining();

}

private void remaining()

{

System.out.println("No.of papers remaining in the Printer: "+counter);

}

}

class Main

{

public static void main(String[] args)

{

Singleton obj1=Singleton.getInstance();

obj1.used();

Singleton obj2=Singleton.getInstance();

}

obj2.used();

}

4. You’re an agent of the R.A.W agency who needs to take in the details of the agents and store them in the database. All the instance variables must be private. Write a program to access and update the details whenever necessary and display them in the following format:

Name: Bond

Age: 42

ID: 007

Location allocated: Britain (Use mutators and accessors) [L.O 3]

Solution:

import java.util.*;

import java.io.*;

class Main

{

private String name,location;

private int age,id;

public void setName(String name)

{

this.name=name;

}

public String getName()

{

return name;

}

public void setAge(int age)

{

this.age=age;

}

public int getAge()

{

return age;

}

public void setLocation(String location)

{

this.location=location;

}

public String getLocation()

{

return location;

}

public void setId(int id)

{

this.id=id;

}

public int getId()

}

{

}

class Type

return id;

 { public static void main(String args[]) { Main M=new Main(); M.setName("Bond"); M.setAge(42); M.setId(007); M.setLocation("Britain"); System.out.println("Name:" +M.getName()); System.out.println("Age:" +M.getAge()); System.out.println("Id:"+ M.getId()); System.out.println("Location:"+ M.getLocation()); } }

5. MATCH THE FOLLOWING

(Assume ‘A’ is the class name)

1. public

[

]

a) Parameterized Constructor

 2. private [ ] b) No-argument constructor 3. A(4,5){ } [ ] c) have only one object 4. Singleton class [ ] d) accessible anywhere 5. A(){ } [ ] e) accessible within the class only 6. Accessors [ ] f) only accessible in class and its subclass 7. Mutators [ ] g) Methods to access instance variables

Solution:

1 - d

2 - e

3 - a

4 - c

5 - b

6 - g

7 - h

h) Methods to initiate instance variables

6) A Restaurant serves dishes of three types: Veg, Non-Veg and Egg represented by green, red and brown color codes respectively. Help them out by writing a menu driven program to display the various dishes depending on the type of food the customer opts for. [L.O 4]

Solution:

import java.util.*;

{

public static void main(String args[])

{

Scanner sc=new Scanner(System.in);

boolean flag = true; while(flag)

{

System.out.print(" Enter your Preference: "); int st=sc.nextInt(); switch(st)

 { case 1: System.out.println(" veg-biriyani\n veg fried rice\n butter naan"); Break; case 2: System.out.println(" chicken-biriyani\n chicken fried rice\n chilli chicken" ); Break; case 3: System.out.println("omlett\n egg fried rice\n egg fry"); Break; case 4: System.out.println("THANK YOU \n"); Break; Default: System.out.println(" category not available "); Break; }

System.out.println("Sir! Enter 1 to Order again"); int sele=sc.nextInt();

if(sele == 1 && st!=4) flag=true; else

{

System.out.println(" VISIT AGAIN\n");

}

}

}

flag=false;

Break;

}

7) A company wants to digitize their manual records of the employee details (Employee ID, Employee name, Employee Department). If all the three fields are given, use the given details. If not, use the default values.

Default values are:

ID: 0

Name: #

Department: #

Solution:

import java.util.*;

class Employee

{

private static int empId;

private static String empName;

private static String empDept;

Employee()

{

empId=0;

empName="#";

empDept="#";

}

Employee(int empId,String empName,String empDept)

 { this.empId=empId; this.empName=empName; this.empDept=empDept; }

public static void main(String args[])

{

Employee e;

Scanner s=new Scanner(System.in);

int n,id;

String name,dept;

System.out.println("Enter number of entries ");

n=s.nextInt();

System.out.println("Enter Employee Id ");

id=s.nextInt();

System.out.println("Enter Employee Name ");

name=s.next()+s.nextLine();

System.out.println("Enter Employee Dept ");

dept=s.nextLine();

if(n<3)

e=new Employee();

else

e=new Employee(id,name,dept);

System.out.println("Employee Id is "+e.empId);

System.out.println("Employee Name is "+e.empName);

System.out.println("Employee Dept is "+e.empDept);

}

}

8) You need to write a program for a government website which maintains the census details of the nation. You need to consider Total, male and female population as the attributes. It should be updated after every census. All the attributes should be private. (Use accessors and mutators to update and retrieve data.) [L.O 3]

Solution:

import java.util.*;

class Census

{

private static int total;

private static int male;

private static int female;

public void setTotal(int total)

{

this.total=total;

}

public void setMale(int male)

{

this.male=male;

}

public void setFemale(int female)

{

this.female=female;

}

public int getTotal()

{

}

public int getMale()

{

return male;

}

public int getFemale()

{

return female;

}

public static void main(String args[])

{

Census c=new Census();

int t,m,f;

Scanner s=new Scanner(System.in);

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

t=s.nextInt();

c.setTotal(t);

System.out.println("Enter number of male ");

m=s.nextInt();

c.setMale(m);

System.out.println("Enter number of female ");

f=s.nextInt();

c.setFemale(f);

System.out.println("Total population is "+c.getTotal());

System.out.println("Employee Name is "+c.getMale());

System.out.println("Employee Dept is "+c.getFemale());

}

}

9) You are working as a Data entry operator in a Sports academy which teaches cricket and football to young kids. As the new calendar year starts a new batch of kids join the academy and you need to store their details. All of them have instance variables as their name, their age and their country in the class player. Depending on the sport the other variables vary, like the class cricketer has matches, runs, wickets, class footballer contains matches and goals. Using these criteria print the data of a cricketer and a footballer using aggregation and composition. [L.O.5]

Solution:

 class player { String Name; int age; String Country; player(String Name,int age,String Country) { this.Name=Name; this.age=age; this.Country=Country; } } class Cricketer {

player PlayerDetails;

int Runs;

int Wickets;

int Matches;

Cricketer(player PlayerDetails,int Runs,int Wickets,int Matches)

 { this.PlayerDetails=PlayerDetails; this.Runs=Runs; this.Wickets=Wickets; this.Matches=Matches; }

void display()

{

System.out.println("

Displaying

a Cricket Player Details

");

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

System.out.println("Age : "+PlayerDetails.age);

System.out.println("Country : "+PlayerDetails.Country);

System.out.println("No of Matches :"+Matches);

System.out.println("No of Runs : "+Runs);

System.out.println("No of Wickets : "+Wickets);

}

}

class FootballPlayer

{

player PlayerDetails;

int Goals;

int Matches;

FootballPlayer(player PlayerDetails,int Matches,int Goals)

 { this.Goals=Goals; this.Matches=Matches; this.PlayerDetails=PlayerDetails; }

void display()

{

System.out.println("

Displaying

a Football Player Details

");