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

OBJECT ORIENTED PROGRAMMING

LABORATORY MANUAL

Dr. Salah Alghyaline


Week-1

Create an employee class (id, name, deptname, salary). Define a default and parameterized
constructor and create two objects of that class.

Dr. Salah Alghyaline


Week-1
solution:
package employee;

public class Employee {

int id;

String name;

String deptname;

double salary;

// Default Constructor

public Employee() {

this.id = 0;

this.name = "";

this.deptname = "";

this.salary = 0.0;

// Parameterized Constructor

public Employee(int id, String name, String deptname, double salary) {

this.id = id;

this.name = name;

this.deptname = deptname;

this.salary = salary;

public static void main(String[] args) {

// Creating objects of Employee class

Employee emp1 = new Employee();

Employee emp2 = new Employee(1, "Sami", "IT", 700);

// Printing employee details

System.out.println("Employee 2 details: ");

System.out.println("ID: " + emp2.id);

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

System.out.println("Department Name: " + emp2.deptname);

System.out.println("Salary: " + emp2.salary);

Dr. Salah Alghyaline


Week-2

1-Activity Create a class, Heater that contains a single integer field, temperature. Define a
constructor that takes no parameters. The temperature field should be set to the value 15 in the
constructor. Define the mutators warmer and cooler, whose effect is to increase or decrease the
value of the temperature by 5 respectively. Define an accessor method to return the value of
temperature.

2-Modify your Heater class to define three new integer fields: min, max, and increment. The values
of min and max should be set by parameters passed to the constructor. The value of increment
should be set to 5 in the constructor. Modify the definitions of warmer and cooler so that they use
the value of increment rather than an explicit value of 5. Before proceeding further, check that
everything works as before. Now modify the warmer method so that it will not allow the
temperature to be set to a value larger than max. Similarly modify cooler so that it will not allow
temperature to be set to a value less than min. Check that the class works properly. Now add a
method, setIncrement that takes a single integer parameter and uses it to set the value of increment.
Once again, test that the class works as you would expect it to, by creating some Heater objects.
Do things still work as expected if a negative value is passed to the setIncrement method? Add a
check to this method to prevent a negative value from being assigned to increment.

Dr. Salah Alghyaline


Week-2
Solution 1:

package heater;

public class Heater {

private int temperature;

public Heater() {

this.temperature = 15;

public void warmer() {

this.temperature += 5;

public void cooler() {

this.temperature -= 5;

public int getTemperature() {

return this.temperature;

public static void main(String[] args) {

Heater heater = new Heater();

System.out.println("Initial temperature: " + heater.getTemperature());

heater.warmer();

System.out.println("Temperature after warmer(): " + heater.getTemperature());

heater.cooler();

System.out.println("Temperature after cooler(): " + heater.getTemperature());

Dr. Salah Alghyaline


Solution 2:
package heater;

public class Heater {

private int temperature;

private int min;

private int max;

private int increment;

public Heater(int min, int max) {

this.temperature = 15;

this.min = min;

this.max = max;

this.increment = 5; }

public void warmer() {

if (this.temperature + this.increment <= this.max) {

this.temperature += this.increment;

} else {

this.temperature = this.max; } }

public void cooler() {

if (this.temperature - this.increment >= this.min) {

this.temperature -= this.increment;

} else {

this.temperature = this.min; } }

public int getTemperature() {

return this.temperature; }

public void setIncrement(int increment) {

if (increment >= 0) {

this.increment = increment;

} }

public static void main(String[] args) {

Heater heater1 = new Heater(10, 20);

Heater heater2 = new Heater(20, 30);

System.out.println("Initial temperature of heater1: " + heater1.getTemperature());

System.out.println("Initial temperature of heater2: " + heater2.getTemperature());

heater1.warmer();

System.out.println("Temperature of heater1 after warmer(): " + heater1.getTemperature());

heater2.cooler();

System.out.println("Temperature of heater2 after cooler(): " + heater2.getTemperature());

heater1.setIncrement(-5);

heater1.warmer();

System.out.println("Temperature of heater1 after setting negative increment and calling warmer(): " + heater1.getTemperature());

}
Dr. Salah Alghyaline
}
Week-3
1. Create a new project according to the following:

a) The name of the main class is (FirstClass).


b) Create an additional class called (SecondClass).
c) In the FirstClass:
• Declare a method that is called DisplayStudentInfo, which prints out the
student's name, gender, university ID number, and the major into different
lines.
• Declare a method that is called FindMaxNumber, which receives 3 integer
numbers, find which number is the maximum number by calling the Math.max
method, then returns the result.
• In the main method call the DisplayStudentInfo method, then read 3 numbers
from the user and call the FindMaxNumber method. The returned result should
be saved in a variable called (savedMax) and then print the returned value and
its multiplication with 10.
2. Overloading methods by changing the number of arguments:
In the SecondClass:
a) Create a class method that is called addNumbers, that receives two integer numbers
and returns the summation of the numbers.
b) Create a class method that is called addNumbers, that receives three integer numbers
and returns the summation of the numbers.
c) Create a class method that is called addNumbers, that receives four integer numbers
and returns the summation of the numbers.
d) In the main method of the FirstClass, call the AddNumbers method three times (using
(the arguments 5,10), (the arguments 5,10,15), and (the arguments 5,10, 15, 20)) and
print out the result of each calling.

Dr. Salah Alghyaline


Solution 1:

import java.util.Scanner;

public class FirstClass {


public static void main(String[] args) {
DisplayStudentInfo();
Scanner input = new Scanner(System.in);
System.out.print("Enter 3 numbers separated by spaces: ");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int savedMax = FindMaxNumber(num1, num2, num3);
System.out.println("The maximum number is: " + savedMax);
System.out.println("The maximum number multiplied by 10 is: " +
savedMax * 10);
}

public static void DisplayStudentInfo() {


System.out.println("Student Name: John Doe");
System.out.println("Gender: Male");
System.out.println("University ID Number: 123456");
System.out.println("Major: Computer Science");
}

public static int FindMaxNumber(int num1, int num2, int num3) {


return Math.max(num1, Math.max(num2, num3));
}
}

Dr. Salah Alghyaline


Solution 2:

public class SecondClass {


public static int addNumbers(int num1, int num2) {
return num1 + num2;
}

public static int addNumbers(int num1, int num2, int num3) {


return num1 + num2 + num3;
}

public static int addNumbers(int num1, int num2, int num3, int num4)
{
return num1 + num2 + num3 + num4;
}
public static void main(String[] args) {
int sum1 = SecondClass.addNumbers(5, 10);
int sum2 = SecondClass.addNumbers(5, 10, 15);
int sum3 = SecondClass.addNumbers(5, 10, 15, 20);
System.out.println("Sum1: " + sum1);
System.out.println("Sum2: " + sum2);
System.out.println("Sum3: " + sum3);

Dr. Salah Alghyaline


Week-4

Create a class called Time that has separate int member data for hours, minutes, and seconds.
Provide

the following member functions for this class:

a. A no-argument constructor to initialize hour, minutes, and seconds to 0.


b. A 3-argument constructor initializes the members to values sent from the calling function
at the time of creation of an object. Make sure that valid values are provided for all the
data members. In case of an invalid value, set the variable to 0.
c. A member function show to display time in 11:59:59 format.
d. A function AddTime for addition of two Time objects. Each time unit of one object must
add into the corresponding time unit of the other object. Keep in view the fact that minutes
and seconds of resultant should not exceed the maximum limit (60). If any of them do
exceed, subtract 60 from the corresponding unit and add a 1 to the next higher unit.

NOTE: Define all the member functions outside the class.


A main() programs should create two initialized Time object and one that is not initialized. Then
it
should add the two initialized values together, leaving the result in the third Time variable. Finally
it should display the value of this third variable.

Dr. Salah Alghyaline


Week-4
Solution:
public class Time {

private int hours;

private int minutes;

private int seconds;

// no-argument constructor

public Time() {

hours = 0;

minutes = 0;

seconds = 0; }

// 3-argument constructor

public Time(int h, int m, int s) {

hours = (h >= 0 && h <= 23) ? h : 0;

minutes = (m >= 0 && m <= 59) ? m : 0;

seconds = (s >= 0 && s <= 59) ? s : 0; }

// display time in 11:59:59 format

public void show() {

System.out.printf("%02d:%02d:%02d", hours, minutes, seconds); }

// add two Time objects

public static Time AddTime(Time t1, Time t2) {

Time result = new Time();

result.seconds = t1.seconds + t2.seconds;

result.minutes = t1.minutes + t2.minutes;

result.hours = t1.hours + t2.hours;

if (result.seconds >= 60) {

result.seconds -= 60;

result.minutes++; }

if (result.minutes >= 60) {

result.minutes -= 60;

result.hours++; }

return result; }}

public class Main {

public static void main(String[] args) {

Time t1 = new Time(11, 30, 0);

Time t2 = new Time(1, 30, 30);

Time t3 = Time.AddTime(t1, t2);

t3.show(); }} Dr. Salah Alghyaline


Week-5

Create a class Employee that has a field for storing the complete name of employee (first and last
name), a field for storing the Identification number of employee, and another field for storing his
salary.

Provide

a) a no-argument constructor for initializing the fields to default values

b) a 3-argument constructor for initializing the fields to values sent from outside.

c) a setter function (mutator) that sets the values of these fields by getting input from user.

d) a function to display the values of the fields.

e) Derive three classes from this employee class: Manager, Scientist, and Laborer. The manager
class has an additional data member of # of subordinates. Scientist class contains additional
information about # of publications. Laborer class is just similar to the employee class. It has no
additional capabilities. Derive a class foreman from the Laborer class that has an additional data
member for storing the percentage of quotas met by a foreman. Provide appropriate no-argument
and n-argument constructors for all the classes.

Dr. Salah Alghyaline


Solution:
import java.util.Scanner;

class Employee {

private String fullName;

private int idNumber;

private double salary;

// No-argument constructor

public Employee() {

this.fullName = "";

this.idNumber = 0;

this.salary = 0.0;

// 3-argument constructor

public Employee(String fullName, int idNumber, double salary) {

this.fullName = fullName;

this.idNumber = idNumber;

this.salary = salary;

// Setter function for all fields

public void setFields() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the employee's full name: ");

this.fullName = sc.nextLine();

System.out.print("Enter the employee's ID number: ");

this.idNumber = sc.nextInt();

System.out.print("Enter the employee's salary: ");

this.salary = sc.nextDouble();

// Display function for all fields

public void displayFields() {

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

System.out.println("Employee ID number: " + this.idNumber);

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

Dr. Salah Alghyaline


class Manager extends Employee {
private int numSubordinates;

// No-argument constructor
public Manager() {
super();
this.numSubordinates = 0;
}

// 4-argument constructor
public Manager(String fullName, int idNumber, double
salary, int numSubordinates) {
super(fullName, idNumber, salary);
this.numSubordinates = numSubordinates;
}

// Setter function for numSubordinates


public void setNumSubordinates() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of subordinates: ");
this.numSubordinates = sc.nextInt();
}

// Display function for all fields


public void displayFields() {
super.displayFields();
System.out.println("Number of subordinates: " +
this.numSubordinates);
}
}

Dr. Salah Alghyaline


class Scientist extends Employee {
private int numPublications;

// No-argument constructor
public Scientist() {
super();
this.numPublications = 0;
}

// 4-argument constructor
public Scientist(String fullName, int idNumber,
double salary, int numPublications) {
super(fullName, idNumber, salary);
this.numPublications = numPublications;
}

// Setter function for numPublications


public void setNumPublications() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of
publications: ");
this.numPublications = sc.nextInt();
}

// Display function for all fields


public void displayFields() {
super.displayFields();
System.out.println("Number of publications: "
+ this.numPublications);
}
}

Dr. Salah Alghyaline


class Laborer extends Employee {
// No-argument constructor
public Laborer() {
super();
}

// 3-argument constructor
public Laborer(String fullName, int idNumber, double
salary) {
super(fullName, idNumber, salary);
}
}

class Foreman extends Laborer {


private double percentQuotasMet;

// No-argument constructor
public Foreman() {
super();
this.percentQuotasMet = 0.0;
}

// 4-argument constructor
public Foreman(String fullName, int idNumber, double
salary, double percentQuotasMet) {
super(fullName, idNumber, salary);
this. percentQuotasMet;
}

Dr. Salah Alghyaline


Week-6

Create a class A class called circle as follows:

• Two private instance variables: radius (of the type of double) and color (of the type String),
with default value of 1.0 and "red", respectively.
• Two overloaded constructors - a default constructor with no argument, and a constructor
which takes a double argument for radius.
• Two public methods: getRadius() and getArea(), which return the radius and area of this
instance, respectively. A public method called setRadius() to set he radius value.

• a subclass called Cylinder is derived from the superclass Circle.


• one private instance variables: height (of the type of double)
• subclass Cylinder invokes the superclass' constructors (via super () and super(radius)) and
inherits the variables and methods from the superclass Circle.
• A constructor with given radius, height
• Two public methods: getHeight() and getVolume()(getArea()*height) , which return the
Height and the Cylinder volume

Dr. Salah Alghyaline


Week-6
Solution:
public class Circle {

private double radius;

private String color;

// Default constructor

public Circle() {

this.radius = 1.0;

this.color = "red";

// Constructor with given radius

public Circle(double radius) {

this.radius = radius;

this.color = "red";

public double getRadius() {

return radius;

public void setRadius(double radius) {

this.radius = radius;

public double getArea() {

return Math.PI * radius * radius;

}}

public class Cylinder extends Circle {

private double height;

public Cylinder(double radius, double height) {

super(radius);

this.height = height; }

public double getHeight() {

return height; }

public double getVolume() {

return getArea() * height;

}}
Dr. Salah Alghyaline
Week-7

Create a class called Point that has two data members: x- and y-coordinates of the point. Provide
a no-argument and a 2-argument constructor. Provide separate get and set functions for the each
of the data members i.e. getX, getY, setX, setY. The getter functions should return the
corresponding values to the calling function. Provide a display method to display the point in (x,
y) format. Make appropriate functions const.
Derive a class Circle from this Point class that has an additional data member: radius of the circle.
The point from which this circle is derived represents the center of circle. Provide a no-argument
constructor to initialize the radius and center coordinates to 0. Provide a 2-argument constructor:
one argument to initialize the radius of circle and the other argument to initialize the center of
circle (provide an object of point class in the second argument). Provide a 3-argument constructor
that takes three floats to initialize the radius, x-, and y-coordinates of the circle. Provide setter and
getter functions for radius of the circle. Provide two functions to determine the radius and
circumference of the circle.Write a main function to test this class.

Dr. Salah Alghyaline


Week-7
Solution:

package point;

public class Point {

private float x;

private float y;

public Point() {

x = 0; y = 0; }

public Point(float x, float y) {

this.x = x;

this.y = y; }

public float getX() {

return x; }

public float getY() {

return y;

public void setX(float x) {

this.x = x; }

public void setY(float y) {

this.y = y; }

public void display() {

System.out.printf("(%.2f, %.2f)\n", x, y);

public static float distance(Point p1, Point p2) {

float dx = p1.getX() - p2.getX();

float dy = p1.getY() - p2.getY();

return (float) Math.sqrt(dx * dx + dy * dy);

Dr. Salah Alghyaline


public static void main(String[] args) {

Point p1 = new Point();

Point p2 = new Point(2.5f, 3.8f);

p1.display();

p2.display();

p1.setX(1.0f);

p1.setY(1.5f);

p1.display();

System.out.printf("Distance between p1 and p2: %.2f\n", distance(p1, p2));

Circle c1 = new Circle();

Circle c2 = new Circle(2.0f, p1);

Circle c3 = new Circle(1.5f, 2.5f, 3.8f);

c1.display();

c2.display();

c3.display();

c1.setRadius(3.0f);

c1.setX(1.0f);

c1.setY(1.5f);

c1.display();

System.out.printf("Area of c1: %.2f\n", c1.getArea());

System.out.printf("Circumference of c1: %.2f\n", c1.getCircumference());

Dr. Salah Alghyaline


class Circle extends Point {

private float radius;

public Circle() {

super();

radius = 0;

public Circle(float radius, Point center) {

super(center.getX(), center.getY());

this.radius = radius;

public Circle(float radius, float x, float y) {

super(x, y);

this.radius = radius;

public float getRadius() {

return radius;

public void setRadius(float radius) {

this.radius = radius;

public float getArea() {

return (float) (Math.PI * radius * radius);

public float getCircumference() {

return (float) (2 * Math.PI * radius);


Dr. Salah Alghyaline
}

}
Week-8
Imagine a publishing company that markets both book and audiocassette versions of its works.
Create a class publication that stores the title (type string) and price (type float) of a publication.
From this class derive two classes: book, which adds a page count (type int); and tape, which adds
a playing time in minutes (type float). Each of these three classes should have a getdata() function
to get its data from the user at the keyboard, and a putdata() function to display its data. Determine
whether public, private, or protected inheritance should be used. Justify your answer.
Write a main() program to test the book and tape classes by creating instances of them, asking
the user to fill in data with getdata() and then displaying the data with putdata().

Dr. Salah Alghyaline


Week-8
Solution:

import java.util.Scanner;

class Publication {
private String title;
private float price;

public void getData() {


Scanner input = new Scanner(System.in);
System.out.print("Enter title: ");
title = input.nextLine();
System.out.print("Enter price: ");
price = input.nextFloat();
}

public void putData() {


System.out.println("Title: " + title);
System.out.println("Price: " + price);
}
}
class Book extends Publication {
private int pageCount;

public void getData() {


super.getData();
Scanner input = new Scanner(System.in);
System.out.print("Enter page count: ");
pageCount = input.nextInt();
}

public void putData() {


super.putData();
System.out.println("Page count: " + pageCount);
}
}

Dr. Salah Alghyaline


class Tape extends Publication {
private float playingTime;

public void getData() {


super.getData();
Scanner input = new Scanner(System.in);
System.out.print("Enter playing time (in minutes): ");
playingTime = input.nextFloat();
}

public void putData() {


super.putData();
System.out.println("Playing time: " + playingTime);
}
}

public class Main {


public static void main(String[] args) {
Book book = new Book();
Tape tape = new Tape();

book.getData();
tape.getData();

System.out.println("Book details:");
book.putData();
System.out.println("Tape details:");
tape.putData();
}
}

Dr. Salah Alghyaline


Week-9
Write a class Triangle , which has two member variables base of type int, and height of type int.

Write a constructor which initializes the base and the height of a Triangle instance.

Write a method getArea() that returns the area of the Triangle as a double.

Write a method show(), to print the dimensions and area of the Triangle instance.

Write a method compare(Triangle t1, Triangle t2), which compares the area of two given
Triangle objects .

Write abstract class circle in another package called “shapes2”.

Write a method in circle class called calcarea to find the area of the circle.

Call the calcarea method from outside the current package.

Dr. Salah Alghyaline


Week-9
Solution:
package triangle;

import shapes2.circle;

class CircleImpl extends circle {

private double radius;

public CircleImpl(double radius) {

this.radius = radius; }

public double calcArea() {

return Math.PI * radius * radius; }}

public class Triangle {

private int base;

private int height;

public Triangle(int base, int height) {

this.base = base;

this.height = height;

public double getArea() {

return 0.5 * base * height; }

public void show() {

System.out.println("Triangle dimensions: base = " + base + ", height = " + height);

System.out.println("Triangle area: " + getArea());}

public static Triangle compare(Triangle t1, Triangle t2) {

if (t1.getArea() > t2.getArea()) {

return t1;

} else if (t2.getArea() > t1.getArea()) {

return t2;

} else {

return null; } }

public static void main(String[] args) {

// Create two Triangle instances and compare their areas

Triangle t1 = new Triangle(4, 5);

Triangle t2 = new Triangle(3, 6);

Triangle largerTriangle = Triangle.compare(t1, t2);

if (largerTriangle != null) {

System.out.println("The larger triangle has an area of " + largerTriangle.getArea());

} else {

System.out.println("The triangles have the same area");

// Create a CircleImpl instance and calculate its area

CircleImpl c = new CircleImpl(2.5);

System.out.println("The area of the circle is " + c.calcArea());


Dr. Salah Alghyaline
}}
package shapes2;

public abstract class circle {

public abstract double calcArea ();

Dr. Salah Alghyaline


Week-10
Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a
50-cent toll. Mostly they do, but sometimes a car goes by without paying. The
tollbooth keeps track of the number of cars that have gone by, and of the total
amount of money collected. Model this tollbooth with a class called tollBooth.
The two data items are a type unsigned int to hold the total number of cars, and a
type of double to hold the total amount of money collected. A constructor
initializes both to 0. A member function called payingCar() increments the car
total and adds 0.50 to the cash total. Another function, called nopayCar(),
increments the car total but adds nothing to the cash total. Finally, a member
function called display () displays the two totals. Make appropriate member
functions const.

Dr. Salah Alghyaline


Week-10
Solution :
public class TollBooth {
private int totalCars;
private double totalCash;

public TollBooth() {
totalCars = 0;
totalCash = 0.0;
}

public void payingCar() {


totalCars++;
totalCash += 0.50;
}

public void nopayCar() {


totalCars++;
}

public void display() {


System.out.println("Total cars: " + totalCars);
System.out.println("Total cash: $" + totalCash);
}
public static void main(String[] args) {
TollBooth tollBooth = new TollBooth();
tollBooth.payingCar();
tollBooth.nopayCar();
tollBooth.payingCar();
tollBooth.display();
}
}

Dr. Salah Alghyaline


Week-11

Q1) Write a java program that:


• The project name TEST and the package name is WISE, and the main class name is Q1.
• Reads a text from data file C:\Ali\source.txt
• do the following:
✓ Counts the words in the text and print the result or display it on the screen.
✓ Counts how many question marks (i.e. ?) in the file and print the result or display it
on the screen.
✓ Finds out how many lines in the file.
• Store the previous result to another file named C:\Rami\Backup.
• Catches the exception if needed in you program.

Dr. Salah Alghyaline


Week-11
Solution:
package WISE;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class Q1 {

public static void main(String[] args) {

// File paths

String inputFilePath = "C:\\Ali\\source.txt";

String outputFilePath = "C:\\Rami\\Backup";

// Initialize counters

int wordCount = 0;

int questionCount = 0;

int lineCount = 0;

try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {

// Read file line by line

String line;

while ((line = reader.readLine()) != null) {

// Count words in the line

String[] words = line.trim().split("\\s+");

wordCount += words.length;

// Count question marks in the line

questionCount += line.length() - line.replace("?", "").length();

// Count lines

lineCount++; }

// Write results to output file

writer.write("Word count: " + wordCount + "\n");

writer.write("Question count: " + questionCount + "\n");

writer.write("Line count: " + lineCount + "\n");

System.out.println("Results saved to " + outputFilePath);

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());


Dr. Salah Alghyaline
e.printStackTrace(); } }}
Week-12
The following UML Class Diagram is provided. Implement all the classes in the Class Diagram.
The getPaidmethods are calculated as follows:
1.For Manager, returns the sum of salary and allowance.
2.For Technician, returns the sum of salary and overtimePay
The toString methods return the following String:
1.For Manager, returns name, salary, allowance, and paid in a String.
2.For Technician, returns name, salary, overtimePay, and paid in a String.

Dr. Salah Alghyaline


Week-12 Solution
// Create an abstract base class Staff
public abstract class Staff {

// Fields of Staff class


protected String name;
protected double salary;

// Constructors of Staff class


public Staff() {

}
public Staff(String name, double salary) {

this.name = name;
this.salary = salary;
}

// Abstract methods of Staff class


public abstract double getPaid();
public abstract String toString();

// Create Manager as a subclass of Staff


class Manager extends Staff{

// Field of Manager class


protected double allowance;

// Constructors of Manager class


public Manager() {
super();
}

public Manager(String name, double salary, double allowance) {


super(name, salary);
this.allowance = allowance;

// Define getPaid in Manager class


@Override
public double getPaid() {

return salary+allowance;
}

// Define toString in Manager class


@Override
public String toString() {

return "Name= " + name + ", Salary = " + salary + ", Allowance = " + allowance + ", Paid = " + getPaid();
}

// Create Technician as a subclass of Staff


class Technician extends Staff{
// Field of Technician class
protected double overtimPay;
// Constructors of Technician class
public Technician() {
super();
}
public Technician(String name, double salary, double overtimPay) {
super(name, salary);
this.overtimPay = overtimPay;

// Define getPaid in Technician class


@Override
public double getPaid() {

return salary+overtimPay;
}
// Define toString in Technician class
@Override
public String toString() {
Dr. Salah Alghyaline
return "Name= " + name + ", Salary = " + salary + ", Allowance = " + overtimPay + ", Paid = " + getPaid();
}

}
Week-13
Write a java code that:
A. Reads a text from data file D:\del\source.txt
B. Counts the words in the text and print the result or display it on the screen.
C. Finds out how many lines in the file and prints the result to another file
named D:\del\Backup.
D. Catches the exception if needed in you program.

Dr. Salah Alghyaline


Week-13
Solution
import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class Q1 {

public static void main(String[] args) {

String inputFilePath = "D:\\del\\source.txt";

String outputFilePath = "D:\\del\\Backup.txt";

try {

// Read text from input file

BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

String line;

int wordCount = 0;

int lineCount = 0;

int questionCount = 0;

while ((line = reader.readLine()) != null) {

// Count words in each line

String[] words = line.split("\\s+");

wordCount += words.length;

// Count lines

lineCount++;

// Count question marks

questionCount += line.chars().filter(ch -> ch == '?').count();

reader.close();

// Print word count and question count to console

System.out.println("Word count: " + wordCount);

System.out.println("Question count: " + questionCount);

// Write line count to output file

BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));

writer.write("Line count: " + lineCount);

writer.close();

} catch (IOException e) {

e.printStackTrace(); } }}
Dr. Salah Alghyaline
Week-14

Read the following files:


- D:\del\file1: contains the following text " Let us first know what is a class and
package in Java".
- D:\del\file2: contains three lines, each line contains " Class in java is a model
for creating objects".
- D:\del\file3: contains two paragraphs as the followings:
a) It means that the properties and actions of the objects are written in class. Properties
are represented by variables and actions of the objects are represented by methods. So,
a class contains variables and methods.
b) The same variables are also available in the objects because they are created from the
class. These variables are also called ‘instance variables’ because they are created
inside the object (instance).
c) Merge the three files as one file with the name and path "D:\del\Allfiles".
d) Make the following statistic for the previous file (i.e. Allfiles):
- Number of lines.
- Number of paragraphs.
- The count number of the word "I "
e) Note that the directory "D:\del" is initiated automatically.

Dr. Salah Alghyaline


Week-14
Solution

import java.io.*;

public class FileProcessor {


public static void main(String[] args) {
try {
// create directory if it does not exist
File directory = new File("D:\\del");
directory.mkdirs();

// read the three input files


BufferedReader reader1 = new BufferedReader(new
FileReader("D:\\del\\file1"));
BufferedReader reader2 = new BufferedReader(new
FileReader("D:\\del\\file2"));
BufferedReader reader3 = new BufferedReader(new
FileReader("D:\\del\\file3"));

// merge the files into a new file


PrintWriter writer = new PrintWriter(new
FileWriter("D:\\del\\Allfiles"));
String line;
while ((line = reader1.readLine()) != null) {
writer.println(line);
}
while ((line = reader2.readLine()) != null) {
writer.println(line);
}
while ((line = reader3.readLine()) != null) {
writer.println(line);
}
reader1.close();
reader2.close();
reader3.close();
writer.close();

Dr. Salah Alghyaline


// count the statistics in the merged file
BufferedReader reader4 = new BufferedReader(new
FileReader("D:\\del\\Allfiles"));
int numLines = 0;
int numParagraphs = 0;
int numI = 0;
boolean newParagraph = true;
while ((line = reader4.readLine()) != null) {
numLines++;
if (newParagraph && !line.trim().isEmpty()) {
numParagraphs++;
newParagraph = false;
}
if (line.contains("I ")) {
numI++;
}
if (line.trim().isEmpty()) {
newParagraph = true;
}
}
reader4.close();

// print the statistics


System.out.println("Number of lines: " +
numLines);
System.out.println("Number of paragraphs: " +
numParagraphs);
System.out.println("Count of the word \"I \": " +
numI);

} catch (IOException e) {
System.out.println("An error occurred: " +
e.getMessage());
}
}
}

Dr. Salah Alghyaline


Week-15

Create a file numbers.txt as follows:

100
9
-89
76
999999
0
-0.1
56

(a) Create a class MyFileManager having the main() loop. Using the BufferedReader class and
the try-catch-finally block, read the contents of numbers.txt.

(b) Inject an exception by giving the name of a non-existent file e.g. foo.txt. Remember to
release resources in the finally block.

(c) Write a user-defined exception - call it NegativeNumberException - to reject negative


numbers while reading a file.
Create a class MyValidator that validates input. [Hint: validateNumbers(...) throws
NegativeNumberException] The exception handling should be such that the programme
continues reading the file even after encountering a negative number.

(d) We have discussed in class that exception handling should not be used for input validation.
Modify the validateNumbers(...) method from part (c) to use input validation for handling
negative numbers gracefully.

Dr. Salah Alghyaline


Week-15
Solution

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

class NegativeNumberException extends Exception {

private static final long serialVersionUID = 1L;

public NegativeNumberException(String message) {

super(message); }}

class MyValidator {

public static void validateNumbers(String input) throws NegativeNumberException {

String[] numbers = input.split("\\s+");

for (String num : numbers) {

if (Double.parseDouble(num) < 0) {

throw new NegativeNumberException("Negative number detected: " + num);

} } }}

public class MyFileManager {

public static void main(String[] args) {

BufferedReader br = null;

try {

File file = new File("numbers.txt");

br = new BufferedReader(new FileReader(file));

String line;

while ((line = br.readLine()) != null) {

try {

MyValidator.validateNumbers(line);

System.out.println(line);

} catch (NegativeNumberException e) {

System.out.println("Error: " + e.getMessage()); } }

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

} finally {

try {

if (br != null) {

br.close(); }

} catch (IOException e) {

System.out.println("Error: " + e.getMessage()); } } }}

Dr. Salah Alghyaline

You might also like