M1086 Chapter 3

You might also like

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

Object Oriented Programming Assignment

1) What are the objects and their properties involved in the solution below
questions:

a) Find the number of blue cars running in Bengaluru?

A: blue colour is the property of the cars, cars are the object and the number of
blue cars is showing the quantity of blue cars running in Bengaluru. (Bengaluru
Refers to Class name here) As it is a specific city of India or showing specific class
name.

b) Find the city where in the road, number of blue cars is maximum?

A: city is the object since it specifies certain city name and road is the class name.
Again, Blue colour is the property of the cars, cars are the object and the number
of blue cars is showing the quantity of blue cars.

2) Justify if a “Car” is a Class or an Object.

A: Car is an Object because Object is instance or instantiation of a class.

3) We have three options as: i) Tiger ii) White Tiger iii) 2 year old White Tiger
named Tipu. Which among these is a class and why?

A: Tiger and White Tiger are the classes A/q to definition of class(class is the
blueprint of an object) and 2 year old white tiger named Tipu is the object since it
refers to specific tiger i.e. 2 year old white tiger named Tipu.

4) What is the necessity of a reference variable?

A: A reference variable provides a new name to existing variable. It is de-


referenced implicitly and does not need a de-referencing operator (*) to retrieve
the value referenced. Reference Variable is a kind of alias. Reference variable are
used as aliases of a variable. References are internal pointer which handled by
internally by compiler or interpreter engine. The major use of a reference variable
to pass a large amount of data (multi dimension array or collection of object) to
function for processing and return back result.

5) When is the address of an objects gets generated?

A: While the default hashcode in the common implementations does use the
object address to generate it, it’s not reversible (and the address being used is an
implementation detail, not a specified functionality). Even if it were possible, the
address of an object can change during the runtime (whereas the default
hashcode doesn’t), so it wouldn’t be a viable approach even if there were a way
to reverse it

6) Can we create a member variable called Dog in a class called Owner?

A: According to questions -: Here’s an example of creating a member variable


called Dog in a class called Owner and a Dog class that contains both private
variables and public methods:

public class Dog extends Animal {

private int numberOfLegs;

private Boolean hasOwner;

public Dog() {

numberOfLegs = 4;

hasOwner = false;

private void bark() {

system.out.println(“Woof!”);

public void move() {


system.out.println(“Running”);

In that example, bark() and the variables numberOfLegs and hasOwner are
private, which means only the Dog class has access to them.

7) What is Encapsulation?

A: In Object Oriented Programming (OOP), encapsulation refers to the bundling


of data with the methods that operate on that data, or the restricting of direct
access to some of an object’s components. Encapsulation is used to hide the
values or state of a structured data object inside a class, preventing direct access
to them by clients in a way that could expose hidden implementation details or
violate state invariance maintained by the methods. Generally, Encapsulation
refers to one or two related but distinct notions, and sometimes to the
combination thereof.

8) How to achieve Encapsulation?

A: Encapsulation in java can be achieved by:

a) Declaring the variables of a class as private.

b) Providing and defining public setter and getter methods to modify and view
the variables values and access them outside the class only through getters and
setters.

Example -:

// save as Employee.java

public class Employee {

private String name;

public String getName() {


return name;

public static void setName(String name) {

this.name = name

//save as EncapTest.java

class EncapTest {

public static void main(String[] args) {

Employee e=new Employee();

e.setname("sumaya");

system.out.println(e.getName());

9) What will happen if getters and setters are made private?

A: If getters and setters are made private then the private getter/setter methods
provide a place for adding extra behavior or error checking code. They can
provide a place for logging state changes or access to the fields.

10) What is the access specifier associated with a constructor?

A: Like methods, constructors can have any of the access modifiers: public,
protected, private, or none (often called package or friendly). Unlike methods,
constructors can take only access modifiers. Therefore, constructors cannot be
abstract , final , native , static , or synchronized .
11) Can we achieve job of a constructor user defined method?

A: Constructor are used to create so that overload will be less on compiler and in
case of member function we need to call it by operators and memory
consumption is higher. A constructor’s purpose is to initialize an object with the
data provided to the constructor and, perhaps more importantly, ensure that the
object is in a consistent and valid state before control is passed back to the calling
program. The purpose of a constructor function is to initialize the data members
that belong to a particular object instance. For example, we have a class that
defines a Person, and specifies that instances have a numeric data member called
age. It’s the role of the constructor to initialize age to a valid initial value
(presumably zero in this case).

12) How to read properties of a Dog object?

A: Object types are defined using classes For EgIf we’re building an application
that records information about dogs, for example, we might want to define a Dog
class so that we can create our own Dog objects, and record the name, weight
and breed of each dog:

As, the things an object knows about itself are its properties. They
represent an object’s state (the data), and each object of that type can have
unique values. So In the above figure: the Dog’s Name, Weight, breed are the
Properties and bark() is a function. A Dog class, for example, might have specific
name, weight and breed properties. The things an object can do are its functions.
They determine an object’s behaviour, and may use the object’s properties. The
Dog class, for example, might have a bark function.

THE CODE:

class Dog (val name: String, var weight: Int, val breed: String) {

13) How can we update age of a dog from 2 to 3 years?


A: We can update age of a dog from 2 to 3 years through this given below code-:

THE CODE-:

import java.util.Scanner;

public class MyPet_1_lab7 {

// Implement the class MyPet_1 so that it contains 3 instance variables

private String breed;

private String name;

private int age;

private double inHumanYears;

// Default constructor

public MyPet_1_lab7() {

this.breed = null;

this.name = null;

this.age = 0;

// Constructor with 3 parameters

public MyPet_1_lab7(String a_breed, String a_name, int an_age){

this.breed = a_breed;

this.name = a_name;

this.age = an_age;

this.inHumanYears = inHumanYears();

}
// Accessor methods for each instance variable

public String getBreed(){

return this.breed;

public String getName(){

return this.name;

public int getAge(){

return this.age;

//Mutator methods for each instance variable

public void setBreed(String a_breed){

this.breed = a_breed;

public void setName(String a_name){

this.name = a_name;

public void setAge(int an_age){

this.age = an_age;

this.inHumanYears = inHumanYears();

public String toString(){


return (this.breed + " whose name is " + this.name + " and " + (double)this.age + "
dog years (" + inHumanYears() + " human years old)");

public boolean equals(MyPet_1_lab7 a){

if ((this.breed.equals(a.getBreed())) && (this.age == a.getAge())){

return true;

else return false;

public double inHumanYears(){

if ((double)age >= 2 ){

inHumanYears = (15 + 9 + (age - 2))*5;

return (inHumanYears);

else

inHumanYears = age*15;

return (inHumanYears);

public double getHumanYears(){

double yearOneAge = age >=1 ? 1.0: age;


double yearTwoAge = age >=2 ? 1.0: age > 1? age-1.0: 0.0;

double yearThreeAge = age > 2 ? age-2.0: 0.0;

inHumanYears = yearOneAge * 15 + yearTwoAge*9 + yearThreeAge * 5;

return inHumanYears;

public static void main(String[] args) {

Scanner keyboard = new Scanner (System.in);

system.out.print("What type of dog do you have? ");

String breed = keyboard.nextLine();

system.out.print("What is its name? ");

String name = keyboard.nextLine();

system.out.print("How old? ");

int age = keyboard.nextInt();

MyPet_1_lab7 dog= new MyPet_1_lab7();

system.out.println(dog);

MyPet_1_lab7 dog1 = new MyPet_1_lab7(breed,name,age);


system.out.println(dog1);

14) How can we delete a Dog Object?

A: We can delete a Dog Object by following ways given below-

a) Using java program, Connect to a database using the getDatabase() method.


b)Get the Dog object of the collection from which we want to delete the
document, using the getCollection() method.

c) Delete the required document invoking the deleteOne() method.

15) Can we create a Dog object without using its constructor?

A: As Constructor is used for both initializing an object and Creating an Object so


we can create a dog object by given below ways-:

a) If we use the third constructor when we create the Dog Object the breed and
name fields are set to our desired values on one statement.

b)If we omit a constructor, the java compiler creates one for us internally. This
default constructor has no parameters and no code so it really does nothing.

16) A retail store wants to keep track of item id and item price of the five items
sold by them. Based on the item purchased by the customer, item price must be
identified and the computation of bill amount must be done as per the price and
quantity of the item purchased. Write a program to implement the above
scenario.

a) Represent the item with their ids and price in array.

b) Search for the item purchased by the customer (assume it to be 5001) in the
item ids arrays and identify the respective price. Display and appropriate error
message if the item is not found in the array.

c) If the item is found i) Compute the bill amount as quantity purchased * price
identified. ii) display the bill id, customer id, purchase id, quantity purchased,
discount and bill amount.

d)Change the purchase item id value to 5006 and run the program again and
observe the result.

A: import java.util.ArrayList;

import java.util.List;
import java.util.Scanner;

class Product {

// properties private String pname;

private int qty;

private double price;

private double totalPrice;

// constructor Product(String pname, int qty, double price, double totalPrice) {

this.pname = pname;

this.qty = qty;

this.price = price;

this.totalPrice = totalPrice;

// getter methods public String getPname() {

return pname;

public int getQty() {

return qty;

public double getPrice() {

return price;

public double getTotalPrice() {


return totalPrice;

// displayFormat public static void displayFormat() {

system.out.print( "\nName Quantity Price Total Price\n");

// display public void display(){

system.out.format("%-9s %8d %10.2f %10.2f\n", pname, qty, price, totalPrice);

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

// variables String productName = null;

int quantity = 0;

double price = 0.0;

double totalPrice = 0.0;

double overAllPrice = 0.0;

char choice = '\0';

// create Scanner class object

Scanner scan = new Scanner(System.in);

List product = new ArrayList();

do {

// read input values

System.out.println("Enter product details,");


system.out.print("Name: ");

productName = scan.nextLine();

system.out.print("Quantity: ");

quantity = scan.nextInt();

system.out.print("Price (per item): ");

price = scan.nextDouble();

// calculate total price for that product

totalPrice = price * quantity;

// calculate overall price

overAllPrice += totalPrice;

// create Product class object and add it to the list

product.add( new Product( productName, quantity, price, totalPrice) );

// ask for continue?

System.out.print("Want to add more item? (y or n): ");

choice = scan.next().charAt(0);

// read remaining characters, don't store (no use)

scan.nextLine();

while (choice == 'y' || choice == 'Y');

// display all product with its properties

Product.displayFormat();

for (Product p : product) {


p.display();

// overall price

system.out.println("\nTotal Price = " + overAllPrice);

// close Scanner scan.close();

17) Create an Employee class with following attributes:

Employee
-empId:int
-empName:string
-empDesign:string
-empDept:string
+employee()
+getters()
+setters()
+employee(int, string, string, string)

Write a program, which creates an instance of employee class and sets the
values for all the attributes.

a) While setting value for empName, setEmpName() method should check for
NullPointer and display appropriate error message.
b) While setting value for empDesig, the designation must have any of the
following values: developer, tester, lead or manager. If none of these values in
matching, then setter method should display “Invalid designation” error
message.

c) While setting value for empDept, the Department must have any of the
following rules: TTH, RCM, Digital, DevOps. If none of these values is matching,
then setter method should display ‘Invalid Dept’ error message.

A: public class Employee {

String name;

String Designation;

String Department;

Employee(String name, String Designation, String Department) {

this.name = name;

this.Designation = Designation;

this.Department = Department;

public static void main(String[] args) {

Employee employee = new Employee("Ashutosh","Engineer","Operations");

system.out.println("Employee Name - %s, Employee Designation - %s, Employee


Department - %s, employee.name,employee.Designation,employee.Department);

18) Develop a program that assists bookstore employees. For each book, the
program should track the book’s title, its price, its year of publication, and the
author’s name. Develop an appropriate Java Class. Create instances of the class
to represent these three books:

a) Daniel Defoe, Robinson Crusoe, $15.50, 1719;

b) Joseph Conrad, Heart of Darkness, $12.80, 1902;

c) Pat Conroy, Beach Music, $9.50, 1996.

A: import java.util.*;

public class BookStore {

String Name, Author, Publication;

double Cost; void input(){

Scanner Sc = new Scanner(System.in);

system.out.print("Enter name of the book : ");

Name = Sc.nextLine();

system.out.print("Enter author : ");

Author = Sc.nextLine();

system.out.print("Enter publication : ");

Publication = Sc.nextLine();

system.out.print("Enter cost : ");

Cost = Sc.nextDouble();

void calculate() {

double Discount = Cost*(13.5 / 100);

double Cost_After = Cost - Discount;


system.out.println("Discount : " + Discount);

system.out.println("Cost after discount : " + Cost_After);

void display() {

system.out.println("Book Name : " + Name);

system.out.println("Author : " + Author);

system.out.println("Publication : " + Publication);

system.out.println("Cost : " + Cost);

public static void main(String args[]) {

BookStore b = new BookStore();

b.input();

b.display();

b.calculate();

19) XYZ bank wants to maintain Customer details. It will register the customer
details whenever a person opens an account with the bank. Below is the
Customer class diagram:
customer

-custId : int

-custName : string

-custAdress : string

-accType : string

-custBalance : double

+getters and setters methods()

At times, the customer registration process changes, here are the guidelines:

1) Admin may register customer by filling only ID, name and address details.

2) Admin may register customer by filling only ID and name.

3) Admin may register customer by filling all the details.

Write an application which implements above scenario. Write main method in


separate class, which creates different customer objects and invokes
appropriate constructors, here is sample code:

Customer customer1 = new Customer(1001, “kumar”, “Rajajinagar, Bangalore10”);

Customer customer2 = new Customer(1002,”Raja”);

Customer customer3 = new Customer(1003, “Shanthi”, “Jayanagar, Bangalore20”,”SB”,1500);


Note: When other data members which are not initialized through constructors
should have appropriate default values.

A: As Register variables tells the compiler to restore, retrieve or manipulate the


variable in CPU register instead of memory Frequently used variables are kept in
registers and they have faster accessibility. We can never get the addresses of
these variables. “register” keyword is used to declare the register variables.

import java.util.*;

public class CustomerDetail {

public static void main (String args []) {

int m, p;

string n, b, c;

double d,a;

system.out.println(" Enter the mobile no., name, DOB , billing address, city ,
res.phone no., Amount outstanding");

m = in.nextInt();

p = in.nextInt();

n = in.nextLine();

b = in.nextLine();

c = in.nextLine();

d = in.nextRead();

a = in.nextRead();

system.out.println("Mobile no." +m);

system.out.println("Name of the customer" +n);


system.out.println("Date of birth:" +d);

system.out.println("Billing address :" +b);

system.out.println("City :" +c);

system.out.println("Residence phone number :" +r);

system.out.println("Amount Outstanding :" +a);

20) Implement below given class diagram, Invoke constructor and methods of
this class by creating appropriate object in main method.

Saving Account
-balance : double
-interestRate : int
-accountNo : int

+savingAccount()
+savingAccount(double, int,int)
+void WithDraw(double amount)
+void CalculateInterest()

Implement the withDraw(double amount) method. If amount is greater than


balance then display error message; otherwise debit amount from balance and
display the message “successfully withdrawn” + amount.

Implement the calculateInterest() method: calculation of simple interest for the


balance maintained in the saving account.

A: import java.util.*;

class bank_account {
String name, type;

long account_number;

double balance_amount;

bank_account(String n, long a, String t, double b) {

name = n;

account_number = a;

type = t;

balance_amount = b;

void deposit(double d) {

if(d > 0) {

balance_amount = balance_amount + d;

else

system.out.println("Invalid Amount");

void withdraw(double w) {

if(w > 0 && w <= balance_amount) {

balance_amount = balance_amount - w;

}
else

system.out.println("Invalid Amount");

void display() {

system.out.println("\nName : " + name);

system.out.println("Balance : " + balance_amount);

public class MyClass {

public static void main(String args[]) {

Scanner Sc = new Scanner(System.in);

String n, t;

long a;

double b;

system.out.print("Enter Name : ");

n = Sc.nextLine();

system.out.print("Enter Account number : ");

a = Sc.nextLong();

System.out.print("Enter Type : ");

t = Sc.nextLine();
system.out.print("Enter Balance : ");

b = Sc.nextDouble();

bank_account bank = new bank_account(n, a, t, b);

bank.display();

system.out.print("\nEnter amount to be deposited : ");

double d = Sc.nextDouble();

bank.diposit(d);

bank.display();

system.out.print("\nEnter amount to be withdrawn : ");

double w = Sc.nextDouble();

bank.withdraw(w);

bank.display();

21) A coffee shop would like to find out the customer feedback rating about its
services. The customer class shown below:
customer

-Name :string

-MobileNo : string

-feedbackRating : double

+customer()

+customer(string ,string,double)

+getters()

+setters()

Example: Assume that the shop will collect feedback from ‘N’ customers.
Following are the sample customer feedback values.

Customer 1: 3 out of 5

Customer 2: 4 out of 5

Customer 3: 2.5 out of 5

Write an application which creates array of ‘N’ customer objects to store


feedback values of these.

A: class ObjectArray {

public static void main(String args[ ]) {

Customer obj[ ] = new Customer[2];

obj[0].setData(1,2);

obj[1].setData(3,4);

system.out.println("For Array Element 0");

obj[0].showData();

system.out.println("For Array Element 1");

obj[1].showData();
}

class Customer {

int a; int b;

public static setData(int c, int d) {

a=c; b=d;

public void showData() {

system.out.println("Value of a = " +a);

system.out.println("Value of b = " +b);

22) Analyze following class diagram and answer below questions.

a) Identify the classes

b) Identify the relationship between each classes

c) Identify the attributes and methods

A: a) Company, Employee, Manager and Contractor are the classes.

b. As the thing an object knows about itself are its properties. They represent an
object’s state(the data), and each object of that type can have unique value.So In
the above figure: the Company’s name, employees, employee’s number, manager
and salary are the properties and
employees[],getName(),getEmployees(),addTeamMembe
r(),getTeamMember(),getSalary(),getemployeeNumber(),
getSalary(),getManager(),getLengthofContract() are the functions. A Company
class for example might have specific name, employees, employee’s number,
manager and salary properties. The Thing an object can do are its functions. They
determine an object’s behaviour, and may use object’s properties. The company
class, for example might have

employees[],getName(),getEmployees(),addTeamMembe
r(),getTeamMember(),getSalary(),getemployeeNumber(),
getSalary(),getManager(),getLengthofContract() functions.

THE CODE -:

Class Company(val empname: String, val employees: String, var Salary: Int, var
empnumber: Int, val Manager: String) {

….

c. As the thing an object knows about itself are its properties. They represent an
object’s state (the data), and each object of that type can have unique value. So In
the above figure: the Company’s name, employees, employee’s number, manager
and salary are the attributes and methods.

23) Write the Starter Class n amed StudentApp.


student

-studentid : int

--studentName : string

_markes : float

-secondchance : boolean

+ student(int,string,string)

+getstudentId() : int

+getStudentName():string

+getMarks() : int

+getScecondChance(): Boolean

+identifyMarks(float): void

+identifyMarks(float,float) : void

A: Class student {

Static int count;

//declaration within class


…….

};

The static data member is defined outside the class or variable or function name
as:

Int student :: count; //definition within class

The definition outside the class is a must.

We can also initialize the static data member at the time of its definition as:

Int student :: count = 0;

If we define 3 objects as:

student obj1, obj2, obj3;

24) Create menu driven program to implement following scenario:

a) Create Student Record

b) Display Student Names in sorted order based on branch (alphabetical order)

c) Display Student ID in ascending order.

A: import java.util.Scanner;
import java.util.Arrays;

class Student {

private long id;

private String name;

private int marks[],total;

Student(long tid, String tname,int tmarks[],int ttotal ) {


id=tid;

name=tname;

marks=tmarks;total=ttotal;

public void setName(String tname) {

name=tname;

public String toString() {

return "regd id = "+ id+" name = "+name + "\n marks in 6 subjects =


"+Arrays.toString(marks) +" Total ="+total;

public long getId() {

return id;

public String getName() {

return name;

public int[] getMarks() {

return marks;

public int getTotal() {

return total;
}

class SearchSort {

public static void sortById(Student st[], int n) {

for(int i=0;i st[j+1].getId())

Student temp = st[j];

st[j]=st[j+1];

st[j+1]=temp;

system.out.println("After sorting based on id, Student details are");

for(int i=0;i st[j+1].getTotal())

Student temp = st[j]; st[j]=st[j+1];

st[j+1]=temp;

system.out.println("After sorting based on total, Student details are");

for(int i=0;i st[j+1].getTotal())


{

Student temp = st[j];

st[j]=st[j+1]; st[j+1]=temp;

system.out.println("After sorting based on total, Student details are");

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

system.out.println(st[i]);

public static int linearSearch(Student st[], int n, int key) {

int flag=0;

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

if(st[i].getId() == key) return i;

return -1;

public static int linearSearch(Student st[], int n, String key) {

int flag=0;

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

{
if(st[i].getName().equalsIgnoreCase(key))

return i;

return -1;

public class StudentDemo {

public static void main(String args[]) {

system.out.println(" 1. Add New Student \n 2. Print details of all students \n 3.


Search a student based on id \n 4. Search based on name \n 5. Modify name
based on id \n 6. Sort based on id \n 7. Sort based on total \n 8. Exit");

Scanner sc = new Scanner(System.in);

int choice = sc.nextInt();

Student st[] = new Student[100];

int nos=0;

while(true){

switch(choice) {

case 1:

system.out.println("enter id, name");

int tid=sc.nextInt();

String tname=sc.next();

int tmarks[]=new int[6];


int ttotal=0;

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

system.out.println("enter marks of subject "+i);

tmarks[i]=sc.nextInt();

ttotal=ttotal+tmarks[i];

st[nos] = new Student(tid,tname,tmarks,ttotal);

nos++; break;

case 2:

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

system.out.println(st[i]);

break;

case 3:

system.out.println("enter id to search");

int key=sc.nextInt();

int index = SearchSort.linearSearch(st,nos,key);

if(index == -1)

system.out.println("search id not found");

else
system.out.println("search element found at index " + index +" student details
are " +st[index]);

break;

case 4:

system.out.println("enter Student name to search");

String key1=sc.next();

index = SearchSort.linearSearch(st,nos,key1);

if(index == -1)

system.out.println("search id not found");

else

system.out.println("search element found at index " + index +" student details


are " +st[index]);

break;

case 5:

system.out.println("enter id whose name to be modified");

int key2=sc.nextInt();

index = SearchSort.linearSearch(st,nos,key2);

if(index == -1)

system.out.println("search id not found");

Else

system.out.println("enter Student name ");


st[index].setName(sc.next());

system.out.println(" student details after modifying name = " +st[index]);

break;

case 6:

SearchSort.sortById(st,nos);

break;

case 7:

SearchSort.sortByTotal(st,nos);

break;

case 8:

System.exit(0);

System.out.println(" 1. Add New Student \n 2. Print details of all students \n 3.


Search a student based on id \n 4. Search based on name \n 5. Modify name
based on id \n 6. Sort based on id \n 7. Sort based on total \n 8. Exit"); choice =
sc.nextInt();

25) Create a method which accepts array of ‘Student’ objects and returns
Student object who has scored highest marks.

Note: Each Student object should have following values:


a) ID

b) Name

c) Branch

d) Score

A: import java.util.*;
class Marks { public static void main() {

Scanner sc=new Scanner(System.in);

int i, max=0;

String name[]=new String[20], x="";

int a[]=new int[20];

system.out.println("Enter marks of 20 students...");

for(i=0;imax)

x=name[i]; max=a[i];

system.out.println("Top Scorer: "+x);

system.out.println("His/Her marks: "+max);

26) Write a menu driven program to implement a solution to manage customers


of a bank with the following options-:
a) Create bank user

b) Update user details

c) Delete user details

d) Display user details

e) EXIT

A: import java.util.Scanner;

class BankDetails {

private String accno;

private String name;

private String acc_type;

private long balance;

Scanner sc = new Scanner(System.in);

//method to open new account

public void openAccount() {

system.out.print("Enter Account No: ");

accno = sc.next();

system.out.print("Enter Account type: ");

acc_type = sc.next();

System.out.print("Enter Name: ");

name = sc.next();

system.out.print("Enter Balance: ");

balance = sc.nextLong();
}

//method to display account details

public void showAccount() {

system.out.println("Name of account holder: " + name);


system.out.println("Account no.: " + accno);

system.out.println("Account type: " + acc_type);

system.out.println("Balance: " + balance);

//method to deposit money

public void deposit() {

long amt; System.out.println("Enter the amount you want to deposit: ");

amt = sc.nextLong();

balance = balance + amt;

//method to withdraw money

public void withdrawal() {

long amt;

system.out.println("Enter the amount you want to withdraw: ");

amt = sc.nextLong();

if (balance >= amt)

balance = balance - amt;


system.out.println("Balance after withdrawal: " + balance);

else

system.out.println("Your balance is less than " + amt + "\tTransaction failed...!!" );


}

//method to search an account number

public boolean search(String ac_no) {

if (accno.equals(ac_no))

showAccount();

return (true);

return (false);

public class BankingApp {

public static void main(String arg[]) {

Scanner sc = new Scanner(System.in);

//create initial accounts

System.out.print("How many number of customers do you want to input? ");


int n = sc.nextInt();

BankDetails C[] = new BankDetails[n];

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

C[i] = new BankDetails();

C[i].openAccount();

// loop runs until number 5 is not pressed to exit

int ch;

do {

system.out.println("\n ***Banking System Application***");

system.out.println("1. Display all account details \n 2. Search by Account


number\n 3. Deposit the amount \n 4. Withdraw the amount \n 5.Exit ");

system.out.println("Enter your choice: ");

ch = sc.nextInt();

switch (ch) {

case 1:

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

C[i].showAccount();

break;
case 2:

system.out.print("Enter account no. you want to search: ");

String ac_no = sc.next();

boolean found = false;

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

found = C[i].search(ac_no);

if (found)

break;

if (!found)

system.out.println("Search failed! Account doesn't exist..!!");

break;

case 3:

system.out.print("Enter Account no. : ");

ac_no = sc.next();

found = false;

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


{

found = C[i].search(ac_no);

if (found)

C[i].deposit()

break;

if (!found)

system.out.println("Search failed! Account doesn't exist..!!");

break;

case 4:

system.out.print("Enter Account No : ");

ac_no = sc.next();

found = false;

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

found = C[i].search(ac_no);

if (found)

{
C[i].withdrawal();

break;

if (!found)

system.out.println("Search failed! Account doesn't exist..!!");

break;

case 5: system.out.println("See you soon...");

break;

while (ch != 5);

You might also like