Java Mandatory 1.1 To 7
Java Mandatory 1.1 To 7
Output Format:
The output should display the welcome message along with the Customer’s name.
Refer sample input and output for formatting specifications.
import java.util.Scanner;
String name;
name=sc.next();
}
}
Total Expenses for the Event
The prime functionality of an Event Management System is budgeting. An Event Management System
should estimate the total expenses incurred by an event and the percentage rate of each of the
expenses involved in planning and executing an event. William, the founder of "Pine Tree" wanted to
include this functionality in his company’s Event Management System.
Write a program to get the branding expenses, travel expenses, food expenses, and logistics
expenses as inputs from the user and calculate the total expenses for an event and the percentage
rate of each of these expenses.
Note :
Formula to calculate percentage = ( Expenses to be found/Total expenses )*100
Input Format:
The first input is a Double value that corresponds to the branding expenses.
The second input is a Double value that corresponds to the travel expenses.
The third input is a Double value that corresponds to the food expenses.
The fourth input is a Double value that corresponds to the logistics expenses.
Output Format:
The first line of the output should display the double value that corresponds to the total expenses for
the Event.
The next four lines should display the percentage rate of each of the expenses.
All the double values should be displayed upto 2 decimal places.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output.]
import java.io.*;
double brand,travel,food,log,total;
double bp,lp,fp,tp;
brand=sc.nextDouble();
travel=sc.nextDouble();
food=sc.nextDouble();
log=sc.nextDouble();
total=(brand+travel+food+log);
bp=(brand/total)*100;
tp=(travel/total)*100;
fp=(food/total)*100;
lp=(log/total)*100;
System.out.println("Total expenses: Rs."+String.format("%.2f",total));
Thrill ride
"Zebra Kingdom" is a brand new Amusement park that is going to be inaugurated shortly in the City
and is promoted as the place for breath-taking charm. The theme park has more than 30 exhilarating
and thrilling rides and as a special feature of the park, the park Authorities have placed many Booking
Kiosks at the entrance which would facilitate the public to purchase their entrance tickets and ride
tickets.
There are few rides in the park that are not suitable for children and aged people, hence the park
Authorities wanted to program the kiosks to issue the tickets based on people’s age. If the age given
is less than 15 (Children) or greater than 60 (Aged), then the system should display as " Not Allowed",
otherwise it should display as "Allowed".
Write a program to implement this functionality.
Input Format:
The first line of the input is an integer that corresponds to the age of the person opting for the ride.
Output Format:
The output should display "Allowed" or "Not Allowed" based on the conditions given.
Refer sample input and output for formatting specifications.
Sample Input 1:
20
Sample Output 1:
Allowed
Explanation:
Sample Input 2:
12
Sample Output 2:
Not Allowed
Explanation:
import java.util.*;
import java.io.*;
class Main{
int age;
age=sc.nextInt();
if(age<15 || age>60)
System.out.println("Not Allowed");
else
System.out.println("Allowed");
}
Star Pattern
Write a program to generate a pattern of stars.
Input and Output Format:
Input consists of a single integer that corresponds to n, the number of rows.
Refer sample input and output for formatting specifications.
import java.util.*;
import java.io.*;
class Main{
int n,i,j;
n=sc.nextInt();
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
System.out.print("*");
}
System.out.println(" ");
Output Format:
The output is a single line series till Nth term, each separated by a space.
Refer sample input and output for formatting specifications.
Sample Input 1:
Sample Output 1:
2 3 5 7 11
Sample Input 2:
10
Sample Output 2:
2 3 5 7 11 13 17 19 23 29
import java.util.*;
int c=0,i=1,j=1,n=0,p;
p=sc.nextInt();
while(n<p)
j=1;
c=0;
while(j<=i)
if(i%j==0)
c++;
j++;
if(c==2)
System.out.printf("\t%d",i);
n++;
i++;
}
OOPS, Classes & Methods / Practice / Mandatory
Write a Java program to get item type, cost per day, and deposit amount from the user and display
these details in a detailed view using the following classes and methods.
[Note :Strictly adhere to the object-oriented specifications given as a part of the problem
statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Please use the below sample convention to create getters and setters of the class ItemType
private String name;
public String getName( ) {
return name;
}
public void setName(String name) {
this.name = name;
}
[All text in bold corresponds to input and the rest corresponds to output.]
MAIN.JAVA
import java.io.*;
import java.util.*;
class Main{
public static void main(String[] args) throws Exception{
}
else{
it.setName(nm);
it.setCostPerDay(cpd);
it.setDeposit(d);
it.display();
}
}
}
ITEM.TYPE.JAVA
import java.text.*;
}
}
Write a Java program to get two users’ details and display whether their phone numbers are the same
or not with the following class and methods.
[Note: Strictly adhere to the object-oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Consider the Main class and write the main method to test the above class.
Sample Input/Output 1:
[All text in bold corresponds to the input and the rest corresponds to output.]
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNumber
9092314562
Enter Name
john
Enter UserName
john@12
Enter Password
john@12
Enter PhoneNumber
9092314562
Same Users
Sample Input/Output 2:
Enter Name
william
Enter UserName
william####
Enter Password
william
Enter PhoneNumber
9092314562
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNumber
9092312102
Different Users
MAIN.JAVA
import java.io.*;
import java.util.*;
class Main{
String i,j,k;long l;
boolean b;
System.out.println("Enter Name");
i=sc.next();
System.out.println("Enter UserName");
j=sc.next();
System.out.println("Enter Password");
k=sc.next();
System.out.println("Enter PhoneNumber");
l=sc.nextLong();
System.out.println("Enter Name");
i2=sc.next();
System.out.println("Enter UserName");
j2=sc.next();
System.out.println("Enter Password");
k2=sc.next();
System.out.println("Enter PhoneNumber");
l2=sc.nextLong();
b=u.comparePhoneNumber(u2);
if(b==true)
System.out.println("Same"+" "+"Users");
else
System.out.println("Different"+" "+"Users");
}
USER.JAVA
this.name=name;
this.username=username;
this.password=password;
this.phoneNumber=phoneNumber;
flag=(user.phoneNumber==phoneNumber);
return flag;
[Note :
Strictly adhere to the object-oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Problem Requirements:
Java
Keyword Min Count Max Count
instanceof 1 -
RECTANGULAR.JAVA
this.length=length;
this.width=width;
this.length=length;
return length;
this.width=width;
return width;
}
public Integer area() {
int a=length*width;
return a;
System.out.println("Rectangle Dimension");
System.out.println("Length:"+length+"\nWidth:"+width);
setLength(rectangleObject.length*newDimension);
setWidth(rectangleObject.width*newDimension);
return rectangleObject;
MAIN.JAVA
import java.io.*;
import java.util.Scanner;
int l,w,d,a;
Rectangle r1,r2;
l=sc.nextInt();
w=sc.nextInt();
r1=new Rectangle(l,w);
r1.display();
a=r1.area();
d=sc.nextInt();
r2=r1.dimensionChange(d);
r2.display();
a=r2.area();
}
Array
Write a Java program to display the array of Integers and array of Strings. Use for each loop to iterate
and print the elements.
Constraints :
Use for each loop to iterate and print the elements.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Problem Requirements:
Java
Keyword Min Count Max Count
for 1 4
MAIN.JAVA
import java.io.*;
import java.util.*;
int n;
System.out.println("Enter n :");
n=sc.nextInt();
num[i] = sc.nextInt();
a[j] = sc.next();
System.out.println(numbers);
System.out.println("Displaying strings");
for(String letters: a)
System.out.println(letters);
Sample Output 1:
Arguments :
Command
Arguments
The number of arguments is 2
Sample Output 2:
Arguments :
Commands
The number of arguments is 1
MAIN.JAVA
import java.io.*;
import java.util.*;
int l=args.length;
System.out.println("Arguments :\n");
for(int i=0;i<l;i++)
System.out.println(args[i]);
Single inheritance
Write a Java program to implement Single Inheritance.
[Note: Strictly adhere to the object oriented specifications given as a part of the problem statement. Use
the same class names and member variable names.
Follow the naming conventions mentioned for getters/setters]
Consider a class named Donor which extends Person class with the following private data members.
Data Type Data Member
String bloodBankName
String donorType
String donationDate
Consider another class Main and write the main method to test the above class.
In the main( ) method, read the person and donor details from the user and call the
displayDonationDetails( ) method.
MAIN.JAVA
import java.io.*;
import java.util.Scanner;
String name=sc.nextLine();
System.out.println("Enter Date of Birth :");
String dateOfBirth=sc.nextLine();
String gender=sc.nextLine();
String mobileNumber=sc.nextLine();
String bloodGroup=sc.nextLine();
String bloodBankName=sc.nextLine();
String donorType=sc.nextLine();
String donationDate=sc.nextLine();
donor.setName(name);
donor.setDateOfBirth(dateOfBirth);
donor.setGender(gender);
donor.setMobileNumber(mobileNumber);
donor.setBloodGroup(bloodGroup);
donor.setBloodBankName(bloodBankName);
donor.setDonorType(donorType);
donor.setDonationDate(donationDate);
donor.displayDonationDetails();
PERSON.JAVA
class Person{
return name;
this.name=name;
return dateOfBirth;
this.dateOfBirth=dateOfBirth;
}
return gender;
this.gender=gender;
return mobileNumber;
this.mobileNumber=mobileNumber;
return bloodGroup;
this.bloodGroup=bloodGroup;
DONOR.JAVA
return bloodBankName;
this.bloodBankName=bloodBankName;
return donorType;
this.donorType=donorType;
return donationDate;
this.donationDate=donationDate;
System.out.println("Name :"+name);
System.out.println("Gender : "+gender);
ABC Bank announced a new scheme of reward points for a transaction using an ATM card. Each
transaction using the normal card will be provided 1% of the transaction amount as a reward point. If a
transaction is made using a premium card and it is for fuel expenses, additional 10 points will be
rewarded. Write a java program to calculate the total reward points.
[Note: Strictly adhere to the object-oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned]
Hint:
Use super keyword to calculate reward points from base class.
Consider the Main class with the main method and read all the transaction details in the main method.
Card type will be either ‘VISA card’ or ‘HPVISA card’. Otherwise, display ‘Invalid data’
Calculate the reward points corresponding to the card type and transaction type and print the reward
points(upto two decimal places).
MAIN.JAVA
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
VISACard visaCard;
String contd;
do{
System.out.println("Enter the transaction detail");
String input=sc.next();
String[] inputs=input.split(",");
if(inputs[2].equals("VISA card")){
visaCard=new VISACard();
double reward=visaCard.computeRewardPoints(inputs[0],Double.parseDouble(inputs[1]));
}
while(contd.equalsIgnoreCase("Yes"));
}
}
HPVISACARD.JAVA
}
}
VISACARD.JAVA
GST Calculation
Write a program to calculate the total amount with GST for the events. The Events are Stage show
and Exhibition. For the Stage show, GST will be 15% and for exhibition, GST will be 5%.
[Note: Strictly adhere to the object oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned]
Override toString() method in all classes to display the event details in the format specified in sample
input and output.
Consider Main class with main method.
In the main() method, read the event details from the user and then create the object of the event
according to the event type.
The total amount will be calculated according to the GST of the corresponding event.
MAIN.JAVA
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in).useDelimiter("\n");
System.out.println("Enter event name");
String name=sc.next();
System.out.println("Enter the cost per day");
double costPerDay=sc.nextDouble();
System.out.println("Enter the number of days");
int noOfDays=sc.nextInt();
System.out.println("Enter the type of event\n1.Exhibition\n2.Stage Event");
int type=sc.nextInt();
Event event;
if(type==1){
}
}
EXHIBITION.JAVA
import java.text.DecimalFormat;
public Exhibition(String name, String type, Double costPerDay, Integer noOfDays, Integer noOfStalls){
super(name,type,costPerDay,noOfDays);
this.name=name;
this.type=type;
this.costPerDay=costPerDay;
this.noOfStalls=noOfStalls;
this.noOfDays=noOfDays;
}
public Double totalCost(){
amt1 = costPerDay*noOfDays*1.05;
return amt1;
}
public String toString(){
return "Event Details\n"+"Name:"+name+"\n"+"Type:"+type+"\n"+"Number of stalls:"+noOfStalls+"\n"+"Total
amount:"+df.format(totalCost());
STAGE EVENT.JAVA
import java.text.DecimalFormat;
public StageEvent(String name, String type, Double costPerDay, Integer noOfDays, Integer noOfStalls){
super(name,type,costPerDay,noOfDays);
this.noOfSeats=noOfStalls;
}
public double totalCost(){
amt = costPerDay*noOfDays*1.15;
return amt;
}
public void display(){
System.out.println("Event Details");
System.out.println("Name:"+name);
System.out.println("Type:"+type);
System.out.println("Number of seats:"+noOfSeats);
System.out.println("Total amount:"+amt);
}
public String toString(){
}
EVENT.JAVA
Abstract Class
Write a program to calculate total cost of the event based on the type of event and display details
using Abstract class and method.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class names,
attribute names and method names should be the same as specified in the problem statement.
Consider a driver class called Main. In the main method, obtain input from the user and create objects
accordingly.
Output format:
Print "Invalid choice" if the input is invalid to our application and terminate.
Display one digit after the decimal point for Double datatype.
Refer to sample Input and Output for formatting specifications.
[All text in bold corresponds to the input and rest corresponds to output]
Sample Input and output 1:
Enter your choice
1.Exhibition
2.StageEvent
1
Enter the details in CSV format
Book expo,Special sale,Academics,Martin,100,1000
Exhibition Details
Event Name:Book expo
Detail:Special sale
Type:Academics
Organiser Name:Martin
Total Cost:100000.0
Sample Input and Output 2:
Enter your choice
1.Exhibition
2.StageEvent
2
Enter the details in CSV format
JJ magic show,Comedy magic,Entertainment,Steffania,5,1000
Stage Event Details
Event Name:JJ magic show
Detail:Comedy magic
Type:Entertainment
Organiser Name:Steffania
Total Cost:5000.0
Sample Input and Output 3:
Enter your choice
1.Exhibition
2.StageEvent
3
Invalid choice
MAIN.JAVA
import java.util.Scanner;
Event event=null;
if(Integer.parseInt(eventType.trim())==1){
System.out.println("Enter the details in CSV format");
String input=sc.next();
String[] inputs=input.split(",");
}
}
STAGE EVENT.JAVA
double calculateAmount() {
return noOfShows*costPerShow;
EXHIBITION.JAVA
public class Exhibition extends Event {
double calculateAmount() {
return noOfStalls*rentPerStall;
}
EVENT.JAVA
Overriding
Overriding is a runtime polymorphism. The inherited class has the overridden method which has the
same name as the method in the parent class. The argument number, types, or return types should
not differ in any case. The method is invoked with the object of the specific class ( but with the
reference of the parent class).
Write a program to calculate projected revenue for exhibition and stage event using inheritance and
method overriding
[Note :
Strictly adhere to the object-oriented specifications given as a part of the problem statement.
Use the same class names and member variable names. ]
Consider a parent class Event and define the following protected attributes,
Attributes Datatype
name String
detail String
ownerName String
Declare the abstract method public abstract Double projectedRevenue() in the Event class
Consider another child class StageEvent that extends Event that defines with the following attribute,
Attributes Datatype
noOfShows Integer
noOfSeatsPerShow Integer
Include appropriate getters and setters.
Prototype for the parameterized constructors to the StageEvent class in the following
order StageEvent(String name, String detail, String ownerName, Integer noOfShows, Integer
noOfSeatsPerShow). Use super( ) to call and assign values in the base class constructor.
Implement the abstract method projectedRevenue() in StageEvent class
MethodName Description
public Double projectedRevenue() Calculate revenue and return the double value. Each seat produces Rs.50 revenue.
Consider the class Main. It includes the method main. In the main( ) method the event details are
read from the user and the methods of the above classes are called
Refer to sample input/output for other further details and format of the output.
The double values should be formatted to 1 decimal place.
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output 1:
Sample Input/Output 2:
MAIN.JAVA
import java.io.IOException;
import java.util.Scanner;
String name=sc.nextLine();
String detail=sc.nextLine();
String owner=sc.nextLine();
int n=sc.nextInt();
switch (n)
case 1:
int stall=sc.nextInt();
break;
case 2:
int show=sc.nextInt();
int seat=sc.nextInt();
break;
STAGE EVENT.JAVA
int noOfShows;
int noOfSeatsPerShow;
super(name,detail,ownername);
this.noOfShows=noOfShows;
this.noOfSeatsPerShow=noOfSeatsPerShow;
return noOfShows*noOfSeatsPerShow*50;
EVENT.JAVA
import java.util.*;
class Event
this.name=name;
this.detail=detail;
this.ownername=ownername;
return 0.0;
}
}
EXHIBITION.JAVA
int noOfStall;
super(name,detail,ownername);
this.noOfStall=noOfStall;
return noOfStall*10000;
MAIN.JAVA
import java.util.*;
import java.io.*;
import java.text.*;
System.out.println("1.Current Account");
System.out.println("2.Savings Account");
Integer n = Integer.parseInt(br.readLine());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
switch (n) {
case 1:
System.out.println("Name");
System.out.println("Account Number");
System.out.println("Account Balance");
break;
case 2:
System.out.println("Name");
System.out.println("Account Number");
System.out.println("Account Balance");
break;
default:
System.out.println("Invalid choice");
break;
}
}
ACCOUNT.JAVA
import java.util.Date;
this.name = name;
return accountNumber;
this.accountNumber = accountNumber;
return balance;
this.balance = balance;
return startDate;
}
this.startDate = startDate;
this.name = name;
this.accountNumber = accountNumber;
this.balance = balance;
this.startDate = startDate;
}
}
MAINTANENCE.JAVA
CURRENT ACCOUNT.JAVA
return 100*noOfYears+200;
}
SAVING ACCOUNT.JAVA
return 2*50*noOfYears+50;
}
}
Interface
Write a program to display different types of Stalls by implementing interface.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class names,
attribute names, and method names should be the same as specified in the problem statement.
Consider a class GoldStall which implements the Stall interface and define the following private
attributes.
Attribute Datatype
stallName String
cost Integer
ownerName String
tvSet Integer
Consider a class PremiumStall which implements the Stall interface and define the following private
attributes.
Attribute Datatype
stallName String
cost Integer
ownerName String
projector Integer
Input Format:
Output Format:
Print “Invalid Stall Type” if the user has chosen the stall type other than the given type
Otherwise, display the details of the stall.
Refer to sample output for formatting specifications.
Note: All Texts in bold corresponds to the input and the rest are output .
import java.util.*;
System.out.println("1)Gold Stall");
System.out.println("2)Premium Stall");
System.out.println("3)Executive Stall");
switch(type)
case 1:
String st1=br.nextLine();
String[] str1=st1.split(",");
GoldStall gd = new
GoldStall(str1[0],Integer.parseInt(str1[1]),str1[2],Integer.parseInt(str1[3]));
gd.display();
break;
case 2:
String st2=br.nextLine();
String[] str2=st2.split(",");
PremiumStall pm = new
PremiumStall(str2[0],Integer.parseInt(str2[1]),str2[2],Integer.parseInt(str2[3]));
pm.display();
break;
case 3:
System.out.println("Enter Stall details in comma-separated(Stall Name, Stall Cost, Owner
Name, Number of Screens)");
String st3=br.nextLine();
String[] str3=st3.split(",");
ExecutiveStall ex = new
ExecutiveStall(str3[0],Integer.parseInt(str3[1]),str3[2],Integer.parseInt(str3[3]));
ex.display();
break;
default:
break;
}
}
EXECUTIVE STALL.JAVA
this.cost = cost;
this.ownerName = ownerName;
this.screen = screen;
return stallName;
this.stallName = stallName;
return cost;
this.cost = cost;
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
return screen;
this.screen = screen;
System.out.println("Cost: Rs."+cost);
}
}
GOLD STALL.JAVA
this.stallName = stallName;
this.cost = cost;
this.ownerName = ownerName;
this.tvSet = tvSet;
System.out.println("Cost: Rs."+cost);
}
}
STALL.JAVA
void display();
}//create interface
PREMIUM STALL.JAVA
this.stallName = stallName;
this.ownerName = ownerName;
this.cost = cost;
this.projector = projector;
System.out.println("Cost: Rs."+cost);
}
}
Round up - Interfaces
Write a program to display different types of notifications for the type of bank chosen by implementing
the interface.
Create an interface named Notification with the following abstract methods
notificationBySms( )
notificationByEmail( )
notificationByCourier( )
The first integer corresponds to select the bank, the next integer corresponds to the type of the
notification.
If there is no valid input then display 'Invalid input'.
[Note: All text in bold corresponds to the input and remaining text corresponds to output]
Problem Requirements:
Java
Keyword Min Count Max Count
interface 1 -
MAIN.JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
ICICI icici;
HDFC hdfc;
if(select == 1){
icici = bankFactory.getIcici();
if(notificationChoice == 1){
icici.notificationBySms();
}else if(notificationChoice == 3) {
icici.notificationByCourier();
} else {
System.out.println("Invalid Input");
hdfc = bankFactory.getHdfc();
if(notificationChoice == 1){
hdfc.notificationBySms();
hdfc.notificationByEmail();
}else if(notificationChoice == 3) {
hdfc.notificationByCourier();
} else {
System.out.println("Invalid Input");
} else {
System.out.println("Invalid Input");
ICICI.JAVA
}
public void notificationByEmail() {
BANK FACTORY.JAVA
NOTIFICATION.JAVA
HDFC.JAVA
[Note: Strictly adhere to the object-oriented specifications given as a part of the problem statement. Use
the same class names, attribute names and method names]
Include appropriate getters and setters for the outer class attributes in both the inner classes.
Get the option for the shape to compute the area and get the attribute according to the shape option
and set the values to the Shape class attributes. Calculate the area and print the area.
Input Format:
Output Format:
import java.util.*;
import java.text.*;
int input=sc.nextInt();
double value1,value2;
switch (input)
case 1:
rectangle.setValue1(sc.nextDouble());
rectangle.setValue2(sc.nextDouble());
break;
case 2:
triangle.setValue1(sc.nextDouble());
triangle.setValue2(sc.nextDouble());
break;
default:
System.out.println("Invalid choice");
SHAPE.JAVA
value1=nextDouble;
return value1;
value2=nextDouble;
return value2;
double ar = getValue1()*getValue2();
return ar;
}
value1=nextDouble;
return value1;
value2=nextDouble;
return value2;
double ar = 0.5*(getValue1()*getValue2());
return ar;
}
Exception Introduction
An exception is an unwanted or unexpected event, which occurs during the execution of a program
i.e at run time, that disrupts the normal flow of the program. There are many types of exception which
can occur due to various reasons. Let's know about each of them in this module.
In this exercise, we'll experiment with Input Mismatch Exception. As the name suggests, when the
input is not compatible with the assigned variable, then Input mismatch exception occurs. Using try
and catch blocks we'll handle the exception.
Create a driver class called Main. In the main method, obtain integer input from the user. If the user
enters a different datatype, prompt the user (Refer I/O) else print the obtained value.
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input and Output 1:
MAIN.JAVA
import java.util.Scanner;
import java.util.InputMismatchException;
try{
int n=sc.nextInt();
// if(n==(int) n)
catch(InputMismatchException g){
System.out.println(g);
}
}
Arithmetic Exception
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e
at runtime, it disrupts the normal flow of the program. For example, there are 10 statements in your
program and there occurs an exception at statement 5, the rest of the code will not be executed i.e.
statement 6 to 10 will not run. If we perform exception handling, the rest of the statement will be
executed. That is why we use exception handling.
Write a program to obtain the cost for 'n' days of an item and n as input and calculate the cost per day
for the item. In case, zero is given as input for n, an arithmetic exception is thrown, handle the
exception and prompt the user accordingly.
Consider a driver class called Main. In the main method, obtain input from the user and store the
values in integer type. Handle exception if one occurs.
The link to download the template code is given below
Code Template
Input format:
The first line of input is an integer which corresponds to the cost of the item for n days.
The second line of input is an integer which corresponds to the value n.
Output format:
If the value of n is zero throws an exception.
Otherwise, print the integer output which corresponds to the cost per day of the item.
[All text in bold corresponds to the input and rest corresponds to the output]
Problem Requirements:
Java
Keyword Min Count Max Count
try 1 -
ArithmeticException 1 -
Keyword Min Count Max Count
catch 1 -
MAIN.JAVA
import java.util.*;
try{
int a=sc.nextInt();
int n=sc.nextInt();
int b=a/n;
catch(ArithmeticException e){
System.out.println(e);
ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException occurs when the program tries to access the array beyond its
size.
Create an array of size 100 and assume it as seat array. Get the tickets to be booked from the
user and handle any exception that occurs in Main Class. At last display all the tickets booked.
The link to download the template code is given below
Code Template
[All Texts in bold corresponds to the input and rest are output]
Problem Requirements:
Java
Keyword Min Count Max Count
ArrayIndexOutOfBoundsException 1 -
catch - -
try 1 -
MAIN.JAVA
import java.util.*;
try{
int k = sc.nextInt();
s[k-1] = 1;
if(s[i]==1)
System.out.println(1+i);
catch(ArrayIndexOutOfBoundsException ade)
System.out.println(ade);
Parse Exception
Write a program to implement ParseException for the given date inputs.
Consider a driver class called Main. In the main method, obtain start time and end time for stage event
show, if an exception occurs, handle the exception and notify the user about the right format.
Input format:
Output format:
[All text in bold corresponds to the input and rest corresponds to the output]
Problem Requirements:
Java
Keyword Min Count Max Count
try 1 -
catch 1 -
ParseException 1 -
MAIN.JAVA
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import java.util.Date;
startd= sc.next();
try {
endd=sc.next();
try{
System.out.println("Start date:"+formatter.format(date));
System.out.println("End date:"+formatter.format(date1));
}catch (ParseException e) {
}
SeatNotAvailableException
An organization is organizing a charity fate for the well being of poor kids. Since the manager was
running short on time, he asked you to help him with the ticket bookings. You being from a
programming background decide to design a program that asks the user about the seat number they
want. Seat booking details are stored in an array. If the seat number requested is available booking
should be done else print the message " SeatNotAvailableException". If the seat number requested is
not in the range throws an exception ArrayIndexOutOfBoundsException.
Write a program to throw a custom exception based on the inputs and constraints given.
In the Main class, create an array of size n*n (n rows each with n seats) which is got from the user.
Get the tickets to be booked from the user and handle any exception that occurs in Main Class. (Take
seat numbers from 0 to (n*n)-1)
Note:
Vacant seats are denoted by (0) and booked seats are denoted by (1).
Show message as "Already Booked" as a Custom exception.
Refer sample Input and Output for formatting specifications.t of the output.
[All Texts in bold corresponds to the input and rest are output]
import java.util.*;
int l;
l=sc.nextInt();
try{
if(arr1d[l]==1)
arr1d[l] = 1;
catch(ArrayIndexOutOfBoundsException ae)
System.out.println(ae);
break;
catch(SeatNotAvailableException e)
System.out.println(e);
break;
int k=0;
arr[i][j]=arr1d[k];
k++;
System.out.print(arr[i][j]+" ");
System.out.println();
import java.util.*;
SeatNotAvailableException(String s)
super(s);
Write an algorithm to generate the Fibonacci Sequence upto to the given number.
Fibonacci Series:
Read number,Set variables j=0,k=1, l=1
FOR: (integer count is less than number, INCREMENT count every loop) DO
PRINT integer j
SET j=k, k=l, l=j+k
END FOR:
Reverse of a number
Input format :
Input consists of an integer value.
Output format :
Output consists of the reverse of the given number.
ELIGIBLE OR NOT?
Pactrick and Johnny found that they have to clear new criteria to play the game. The eligibility
criteria for playing the game is that the participant should be above 10 years and his/ her height
should be above 140cm. (Both 10 and 140 are inclusive). If a participant is eligible he / she will be
allowed inside. Both Patrick and Johnny wanted to know whether they are eligible to play. Write a
program to find whether a participant is eligible or not.
Input Format:
Input consists of two integers which corresponds to age and height of a person (in cms) respectively.
Output Format :
[All text in bold corresponds to input and the rest corresponds to output]