Indira Gandhi Delhi Technical University for Women
(Established by Govt. of Delhi vide Act 09 of 2012)
Kashmiri Gate, Delhi – 110006
Project File
OBJECT ORIENTED PROGRAMMING - JAVA
OOPJ
(BAI-102)
Submitted to: Submitted by:
Mrs. Shweta Tanu Raman
14401172022
2nd Semester
Index
S. no. Experiment Date Signature
1. Lab – 1 : Basic questions 23.03.23
2. Lab – 2 : Pattern and loop 29.03.23
3. Lab – 3: Switch statement 06.04.23
4. Lab – 4 : Calendar and matrix 26.04.23
5. Lab – 5 : Constructor 03.05.23
6. Lab – 6 : Inheritance 21.05.23
7. Lab – 7 : Constructor and overriding 31.05.23
8. Lab – 8 : File handling 07.06.23
9. Lab – 9 : Exception handling 14.06.23
Q1. WAP to print whether a given number is even or odd.
Output:
Q2. WAP to swap two numbers without taking a 3rd variable.
Output:
Q3. WAP to find a maximum of 3 numbers.
Output:
Q4. WAP to print the grace of a student as per given marks
‘A’ for marks>80
‘B’ marks between 70-80
‘C’ marks between 60-70
‘D’ marks between 50-60
‘F’ for marks less than 50.
Output:
Q5. WAP to find the roots of a quadratic equation.
Output:
Q6. Print (a+(b*c))/(b-c) taking a, b, c as input.
Output:
Q7. Print table of a number taken from the user.
Output:
Q8. Convert rupees, taken as input, to paise.
Output:
Q9. Print following paTern
Output:
Q10. Create calculator.
import [Link];
class Ten
{
public static void main(String []args)
{
[Link]("Calculator");
int a, b, c;
Scanner scanner = new Scanner([Link]);
[Link]("First value: ");
a = [Link]();
[Link]("Second value: ");
b = [Link]();
[Link]("Function to be performed (+, -, *, /)");
char op = [Link]().charAt(0);
if (op == '+')
{
c = a + b;
[Link](c);
}
else if (op == '-')
{
c = a - b;
[Link](c);
}
else if (op == '*')
{
c = a * b;
[Link](c);
}
else if (op == '/')
{
c = a * b;
[Link](c);
}
else
{
[Link]("Can't perform the specified action.");
}
}
}
Output:
Q11. Create calculator using Switch.
import [Link];
public class Eleven {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("First value: ");
int a = [Link]();
[Link]("Second value: ");
int b = [Link]();
[Link]("Enter the operator \n1 for sum \n2 for difference \n3
for product \n4 for division: ");
int op = [Link]();
int result;
switch (op) {
case 1:
result = a + b;
[Link]("The sum is: " + result);
break;
case 2:
result = a - b;
[Link]("The difference is: " + result);
break;
case 3:
result = a * b;
[Link]("The product is: " + result);
break;
case 4:
if (b != 0) {
result = a / b;
[Link]("The division is: " + result);
} else {
[Link]("Error");
}
break;
default:
Output:
Q12. WAP to convert temp from degree Celsius to degree Fahrenheit.
Output:
Q13. WAP to print whether a given number is positive, negative or
zero.
Output:
Q14. WAP to find whether a year is a leap or not.
Output:
Q15. WAP to find whether a given character is a vowel or consonant.
Output:
Q16. WAP to print the name of the month and the number of days for
given no (1-12). E.g.- 3- March 31 days.
import [Link];
class Sixteen
{
public static void CheckYear(){
int Year;
[Link]("Write the year: ");
Scanner scanner = new Scanner([Link]);
Year = [Link]();
if (Year%4==0){
if (Year%400==0){
[Link]("February : 29 days");
}
else if (Year%100==0){
[Link]("February : 28 days");
}
else {
[Link]("February : 29 days");
}
}
else {
[Link]("February : 28 days");
}
[Link]();
}
public static void main(String []args)
{
int Number;
[Link]("Write a Number between 1 and 12: ");
Scanner scanner = new Scanner([Link]);
Number = [Link]();
if (Number == 1){
[Link]("January : 31 days");
}
else if (Number == 2){
CheckYear();
}
else if (Number == 3){
[Link]("March : 31 days");
}
else if (Number == 4){
Output:
Q17. Create a calendar, enter date to get its previous date, next date,
and day.
import [Link];
public class Seventeen {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the date, DD: ");
int day = [Link]();
[Link]("Enter the month, MM: ");
int month = [Link]();
[Link]("Enter the year, YYYY:
"); int year = [Link]();
int daysInMonth = 0;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31;
break;
case 4: case 6: case 9: case 11:
daysInMonth = 30;
break;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
}
int previousDay = day - 1;
int previousMonth = month;
int previousYear = year;
if (previousDay < 1) {
previousMonth--;
if (previousMonth < 1) {
previousYear--;
previousMonth = 12;
}
previousDay = daysInMonth;
}
int nextDay = day + 1;
int nextMonth = month;
int nextYear = year;
if (nextDay > daysInMonth) {
nextMonth++;
if (nextMonth > 12) {
nextYear++;
nextMonth = 1;
}
Output:
Q18. Use 2D array to print matrix, perform addition and
multiplication on it with another matrix.
int[][] matrix2 = new int[rows2][columns2];
[Link]("Enter elements of second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < columns2; j++) {
matrix2[i][j] = [Link]();
}
}
// Print
[Link]("First matrix:");
printMatrix(matrix1);
[Link]("Second matrix:");
printMatrix(matrix2);
// Addition
if (rows1 == rows2 && columns1 == columns2) {
int[][] sumMatrix = new int[rows1][columns1];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns1; j++) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
[Link]("Sum of matrices:");
printMatrix(sumMatrix);
} else {
[Link]("Matrices cannot be added.");
}
// Multiplication
if (columns1 == rows2) {
int[][] productMatrix = new int[rows1][columns2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
for (int k = 0; k < columns1; k++) {
productMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
[Link]("Product of matrices:");
printMatrix(productMatrix);
} else {
[Link]("Matrices cannot be multiplied.");
}
}
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[0].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
Output:
Q19. Create a class triangle having color, type, side 1,2,3, depending
on the type of triangle, call constructor and calculate and print area.
public class Nineteen {
String color;
double side1;
double side2;
double side3;
Nineteen(String color,double side1, double side2, double side3) {
[Link] = color;
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
double calculateArea() {
double s = (side1 + side2 + side3) / 2;
double area = [Link](s * (s - side1) * (s - side2) * (s - side3));
return area;
}
void printArea() {
double area = calculateArea();
[Link]("The area of the triangle is: " + area);
}
void getType(){
if(side1==side2 && side2==side3){
[Link]("Equilateral");
}
else{
if(side1!=side2 && side2!=side3 && side3!=side1){
[Link]("Scalene");
}
else{
[Link]("Isosceles");
}
}
}
public static void main(String[] args) {
// Example usage
Nineteen triangle = new Nineteen("Red", 5.0, 7.0, 8.0);
[Link]();
[Link]();
}
}
Output:
Q20. WAP to create a class Account having account no., name,
balance, rate of interest, type (savings and current)
Write code for possible operagons:
1. Create account
2. Check Balance
3. Update Balance
4. Withdraw
5. Deposit
6. Exit
public void withdraw(Float amount) {
if (amount > balance) {
[Link]("Insufficient balance. Withdrawal failed.");
} else {
balance -= amount;
[Link]("Withdrawn Amount: " + amount);
[Link]("Updated Balance: " + balance);
}
}
public void deposit(Float amount) {
balance += amount;
[Link]("Deposited Amount: " + amount);
[Link]("Updated Balance: " + balance);
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Twenty account = null;
int choice;
do {
[Link]("----- Account Menu ");
[Link]("1. Create Account");
[Link]("2. Check Balance");
[Link]("3. Update Balance");
[Link]("4. Withdraw");
[Link]("5. Deposit");
[Link]("6. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter Account Number: ");
int accountNumber = [Link]();
[Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Initial Balance: ");
Float balance = [Link]();
[Link]("Enter Interest Rate: ");
Float interestRate = [Link]();
[Link](); // Consume the newline character
[Link]("Enter Account Type (Savings/Current): ");
String accountType = [Link]();
account = new Twenty(accountNumber, name, balance,
interestRate, accountType);
[Link]("Account Created Successfully!");
break;
case 2:
if (account != null) {
[Link]();
} else {
[Link]("No account found");
}
break;
case 3:
if (account != null) {
[Link]("Enter the
amount to update the
");
balance:
Float amount =
[Link]();
[Link](amoun
t);
} else {
[Link]("No
account found");
}
break;
case 4:
if (account != null) {
[Link]("Enter the amount to withdraw: ");
Float amount = [Link]();
[Link](amount);
} else {
[Link]("No account found");
}
break;
case 5:
if (account != null) {
[Link]("Enter the amount to deposit: ");
Float amount = [Link]();
[Link](amount);
} else {
[Link]("No account found");
}
break;
case 6:
[Link]("Exiting");
break;
default:
[Link]("Invalid choice");
}
[Link]();
} while (choice != 6);
[Link]();
}
}
Output:
Q21. Create base class distance, give private parameter d1. Create
constructors for add, subtract and print. Two derived classes
Dinch(convert d1 to inches) Dmiles( convert d1 to miles), give them
the same constructors. Use override to print and add.
public class TwentyOne {
public static void main(String[] args) {
class Distance {
double d1;
Distance(double d1) {
this.d1 = d1;
}
double getD1() {
return d1;
}
void setD1(double d1) {
this.d1 = d1;
}
void add(Distance other) {
d1 += other.getD1();
}
void subtract(Distance other) {
d1 -= other.getD1();
}
void print() {
[Link]("Distance: " + d1 + " units");
}
}
class Dinch extends Distance {
Dinch(double d1) {
super(d1);
}
void print() {
[Link]("Distance: " + getD1() + " inches");
}
void add(Distance other) {
double inches = ((Dinch) other).getD1();
d1 += inches;
}
}
class Dmiles extends Distance {
Output:
Q22. Create an employee class with private members name address
age gender taken as input, use constructor to initialize values to the
variable, display all. Derive employee class into full time employee,
with members salary and designation (display all) and part time
employee with members work hour and rate per hour from which pay
can be calculated (work hour * rate per hour), display pay.
import [Link];
class Employee {
String name, address, gender;
int age;
public Employee(String name, String address, int age, String gender) {
[Link] = name;
[Link] = address;
[Link] = age;
[Link] = gender;
}
public void display() {
[Link]("Name: " + name);
[Link]("Address: " + address);
[Link]("Age: " + age);
[Link]("Gender: " + gender);
}
}
class FullTimeEmployee extends Employee {
Float salary;
String designation;
FullTimeEmployee(String name, String address, int age, String gender, Float
salary, String designation) {
super(name, address, age, gender);
[Link] = salary;
[Link] = designation;
}
@Override
public void display() {
[Link]();
[Link]("Salary: " + salary);
[Link]("Designation: " + designation);
}
}
class PartTimeEmployee extends Employee {
Float workHours;
Float ratePerHour;
PartTimeEmployee(String name, String address, int age, String gender, Float
workHours, float ratePerHour) {
super(name, address, age, gender);
[Link] = workHours;
[Link] = ratePerHour;
}
float calculatePay() {
return workHours * ratePerHour;
}
@Override
public void display() {
[Link]();
Float pay = calculatePay();
[Link]("Pay: " + pay);
}
}
public class TwentyTwo{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter details for Full-Time Employee:");
[Link]("Name: ");
String name = [Link]();
[Link]("Address: ");
String address = [Link]();
[Link]("Age: ");
int age = [Link]();
[Link]();
[Link]("Gender: ");
String gender =
[Link]();
[Link]("Salary: $");
Float salary =
[Link]();
[Link]();
[Link]("Designation: ");
String designation = [Link]();
[Link]();
FullTimeEmployee fullTimeEmployee = new FullTimeEmployee(name, address,
age, gender, salary, designation);
[Link]("Full-Time Employee Details:");
[Link]();
[Link]();
[Link]("Enter details for Part-Time Employee:");
[Link]("Name: ");
String pname = [Link]();
[Link]("Address: ");
String paddress = [Link]();
[Link]("Age: ");[Link];
Output:
Q23. Define a class motor vehicle having members model name,
model no. and model price having method display() to display the
name, no. and price. Define another class Car that inherits the class
Motor vehicle which has the member disRate and methods display()
to display name, no., price, disRate and discount() to compute
discount rate. Create the classes with suitable constructors and
test for 2 objects.
import [Link];
class MotorVehicle{
Scanner scan = new Scanner([Link]);
String ModelName;
int ModelNumber;
int ModelPrice;
void read(){
[Link]("Model Name = ");
ModelName = [Link]();
[Link]("Model Number = ");
ModelNumber = [Link]();
[Link]("Model Price = ");
ModelPrice = [Link]();
}
void display(){
[Link]("Model Name : " + ModelName + " Model Number : " +
ModelNumber + " Model Price : " + ModelPrice);
}
}
class Car extends MotorVehicle{
int disRate;
void read(){
[Link]();
[Link]("Discount Rate = ");
disRate = [Link]();
}
void display(){
[Link]();
[Link]("Discount Rate : " + disRate);
}
void discount(){
[Link](ModelPrice - (ModelPrice*disRate/100));
}
}
public class TwentryThree{
public static void main(String[] args) {
MotorVehicle A = new MotorVehicle();
Output:
Q24. Create an interface shape having function read, print and
calcarea with no parameters and return type as void implement the
interface in classes circle , triangle and rectangle. B) create an array of
ten objects instantiate to be of type circle, triangle, rectangle as per
user's choice.
[Link]("What is the value of radius? ");
r = [Link]();
[Link]();
}
public void print(){
[Link]("Area of the Circle is : 3.14 * r * r ");
}
public void calArea(){
[Link](3.14*r*r);
}
class Triangle implements Shapes{
int b, h;
public void read(){
Scanner scan = new Scanner([Link]);
[Link]("What is the value of height? ");
h = [Link]();
[Link]("What is the value of base? ");
b = [Link]();
[Link]();
}
public void print(){
[Link]("Area of the Triangle is : b*h/2 ");
}
public void calArea(){
[Link](b*h/2);
}
}
class Rectangle implements Shapes{
int l, b;
public void read(){
Scanner scan = new Scanner([Link]);
[Link]("What is the value of length? ");
l = [Link]();
[Link]("What is the value of breadth? ");
b = [Link]();
[Link]();
}
public void print(){
[Link]("Area of the Rectangle is : l*b ");
}
public void calArea(){
[Link](l*b);
}
}
class TwentyFour{
public static void main(String[] args) {
Output:
Q25. An educational institution wishes to maintain a database of its
employees. The database is divided into several classes whose
hierarchical relationships are shown in the figure below. The figure
also shows the minimum information required for each class. Specify
all the classes and define methods to create the database and retrieve
individual information as and when required. Implement this
application by creating multiple classes and storing them in different
files. Also, write a driver class called college and illustrate the
execution of this application.
class Staff{
String code, name;
Staff(String code, String name){
[Link] = code;
[Link] = name;
}
void print(){
[Link]("Code is : " + code);
[Link]("Name is : " + name);
}
}
class Teacher extends Staff{
String subject, publication;
Teacher(String code, String name, String subject, String publication){
super(code, name);
[Link] = subject;
[Link] = publication;
}
void print(){
[Link]();
[Link]("Subject is : " + subject);
[Link]("Publication is : " + publication);
}
}
class Typist extends Staff{
int speed;
Typist(String code, String name, int speed){
super(code, name);
[Link] = speed;
}
void print(){
[Link]();
[Link]("Speed is : " + speed);
}
}
class Officer extends Staff{
String grade;
Officer(String code, String name, String grade){
super(code, name);
[Link] = grade;
}
void print(){
[Link]();
[Link]("Speed is : " + grade);
}
}
class Regular extends Typist{
Regular(String code, String name, int speed){
super(code, name, speed);
}
}
class Casual extends Typist{
int wage;
Casual(String code, String name, int speed, int wage){
super(code, name, speed);
[Link] = wage;
}
void print(){
[Link]();
[Link]("Daily Wage is : " + wage);
}
}
public class TwentyFive{
public static void main(String[] args) {
Staff A = new Staff("ABC", "me");
Teacher B = new Teacher("DEF", "Riya", "OOPS", "NA");
Typist C = new Typist("GHJ", "Priya", 60);
Officer D = new Officer("KJN","Den", "A");
Casual E = new Casual("HJHMN", "John", 70, 10000);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Q26. Create a file to read input from file 1 and copy its content to file
2.
import [Link].*;
public class copycontent {
public static void main(String[] args) throws IOException {
File F1 = new File ("[Link]");
File F2 = new File ("[Link]");
FileInputStream fis = new FileInputStream(F1);
FileInputStream fis1 = new FileInputStream(F2);
int num = [Link]();
int num1 = [Link]();
byte b1[] = new byte[num];
[Link](b1);
byte b2[] = new byte[num1];
[Link](b2);
String s = new String(b1);
String s1 = new String(b2);
[Link]("File 1 Contents");
[Link](s);
[Link]("File 2 Contents");
[Link](s1);
s1 = s;
[Link]();
[Link]();
FileOutputStream fos = new FileOutputStream(F1);
[Link](b1);
FileOutputStream fos1 = new FileOutputStream(F2);
[Link](b2);
[Link]("New File 2 Content = " + s1);
[Link]();
[Link]();
}
}
Output:
_________________________________________________________________
Q27. WAP to count the no. of blank spaces from file and delete them
import [Link].*;
public class blank {
public static void main(String[] args) throws IOException {
File F1 = new File("[Link]");
FileInputStream fis = new FileInputStream(F1);
int num = [Link]();
byte b[] = new byte[num];
[Link](b);
String s = new String(b);
[Link]("File Contents");
[Link](s);
byte b1[] = new byte[num];
String bs = " ";
int count = 0;
for (int i = 0; i < num; i++) {
int j = 0;
if ([Link](i) == ' ') {
count++;
} else {
b[j] = (byte) [Link](i);
j++;
bs = bs + [Link](i);
}
}
FileOutputStream fos = new FileOutputStream(F1);
[Link](b1);
[Link]("No. of spaces deleted = " + count);
[Link]("New Content = " + bs);
[Link]();
}
}
Output:
Q28. WAP to read a file and count the number of vowels.
import [Link].*;
public class vowelcount {
public static void main(String[] args) throws IOException {
File F1 = new File("[Link]");
FileInputStream fis = new FileInputStream(F1);
int num = [Link]();
byte b[] = new byte[num];
[Link](b);
String s = new String(b);
[Link]("File Contents");
[Link](s);
byte b1[] = new byte[num];
int count = 0;
for (int i=0; i < num; i++){
if([Link](i) == 'A' || [Link](i) == 'E' || [Link](i) == 'I' || [Link](i) == 'O'
||[Link](i) == 'U' || [Link](i) == 'a' || [Link](i) == 'e' || [Link](i)
== 'i' ||
[Link](i) == 'o' || [Link](i) == 'u')
{
countv++;
}
}
FileOutputStream fos = new FileOutputStream(F1);
[Link](b1);
[Link]("No. of vowels in file = " + count);
[Link]();
}
}
Output:
Q29. WAP to read two files and concatenate the input into the third
file.
import [Link].*;
public class concatenate {
public static void main(String[] args) throws IOException {
File F1 = new File ("[Link]");
File F2 = new File ("[Link]");
File F3 = new File ("[Link]");
FileInputStream fis = new FileInputStream(F1);
FileInputStream fis1 = new FileInputStream(F2);
FileInputStream fis2 = new FileInputStream(F3);
int num = [Link]();
int num1 = [Link]();
int num2 = [Link]();
byte b1[] = new byte[num];
[Link](b1);
byte b2[] = new byte[num1];
[Link](b2);
byte b3[] = new byte[num2];
[Link](b3);
String s = new String(b1);
String s1 = new String(b2);
String s2 = new String(b3);
s2= s+s1;
[Link]("File 1 Contents");
[Link](s);
[Link]("File 2 Contents");
[Link](s1);
[Link]("File 3 Contents (concatenated file1 and file2)");
[Link](s2);
[Link]();
[Link]();
[Link]();
FileOutputStream fos = new FileOutputStream(F1);
[Link](b1);
FileOutputStream fos1 = new FileOutputStream(F2);
[Link](b2);
FileOutputStream fos2 = new FileOutputStream(F2);
[Link](b3);
[Link]();
[Link]();
[Link]();
}
}
Output:
Q30. WAP to read a file and replace a vowel with blank space.
import [Link].*;
public class intro {
public static void main(String[] args) throws IOException {
File F1 = new File("[Link]");
FileInputStream fis = new FileInputStream(F1);
int num = [Link]();
byte b[] = new byte[num];
[Link](b);
String s = new String(b);
[Link]("File Contents: ");
[Link](s);
byte b1[] = new byte[num];
int countv = 0;
String bs = " ";
for (int i=0; i < num; i++){
if([Link](i) == 'A' || [Link](i) == 'E' || [Link](i) == 'I' || [Link](i) == 'O'
||[Link](i) == 'U' || [Link](i) == 'a' || [Link](i) == 'e' || [Link](i)
== 'i' ||
[Link](i) == 'o' || [Link](i) == 'u')
{
countv++;
int count = 0;
for (int j = 0; j < num; j++) {
int k = 0;
if ([Link](j) == ' ') {
count++;
} else {
b[k] = (byte) [Link](j);
k++;
bs = bs + [Link](j);
}
}
}
}
FileOutputStream fos = new FileOutputStream(F1);
[Link](b1);
[Link]("No. of vowels in file = " + countv);
[Link]("New File Content: " + bs);
[Link]();
}
}
Output:
_________________________________________________________________
Q31. WAP to create a file to save employee details, designagon,
salary, department. Write the details in the file as an object and read
and print.
import [Link].*;
class Employee_Details implements Serializable{
String Name;
String Designation;
int Salary;
String Department;
Employee_Details (String n, String des, int s, String dep){
[Link] = n;
[Link] = des;
[Link] = s;
[Link] = dep;
}
void Read_Details (String n, String des, int s, String dep){
Name = n;
Designation = des;
Salary = s;
Department = dep;
}
void Print_Details(){
[Link]("Name of the Employee" + Name);
[Link]("Designation of the Employee" + Designation);
[Link]("Salary of the Employee" + Salary);
[Link]("Department of the Employee" + Department);
}
}
public class main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Employee_Details e1 = new Employee_Details("abc", "Manager", 10000, "Sales");
Employee_Details e2 = new Employee_Details("def", "Manager", 100000, "Marketing");
FileOutputStream fos = new FileOutputStream ("Employee_Details");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](e1);
[Link]();
FileInputStream fis = new FileInputStream("Employee_Details");
ObjectInputStream ois = new ObjectInputStream (fis);
e2 = (Employee_Details) [Link]();
[Link]("Name of the Employee: " + [Link]);
[Link]("Designation of the Employee: " + [Link]);
[Link]("Salary of the Employee: " + [Link]);
[Link]("Department of the Employee: " + [Link]);
}
}
Output:
Q32. WAP that reads two integers and runs a loop for calculating ab .
You must check if b=0, then throw an exception and handle it by a/b.
Catch the exception and let the code continue until there is no
exception. Give ‘Hi’ and ‘Bye’ statements for every block of code.
import [Link].*;
public class lab {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Hi Main!");
[Link](" ");
while (true) {
try {
[Link]("Hi try!");
[Link](" ");
[Link]("Enter the value of a: ");
int a = [Link]();
[Link]("Enter the value of b: ");
int b = [Link]();
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
int result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
[Link]("a^b = " + result);
[Link]("Bye try!");
[Link](" ");
break;
}
catch (ArithmeticException a) {
[Link]("Hi catch!");
[Link](" ");
[Link]("Exception: " + [Link]());
[Link]("Handled by performing a/b.");
[Link]("Answer: Infinity");
[Link]("Bye catch!");
[Link](" ");
}
}
[Link]("Bye Main!");
}
}
Output: