Java oop assignments questions and answers, Assignments of Java Programming

Java oop assignments questions and answers

Typology: Assignments

2022/2023

Available from 05/04/2023

t-meral
t-meral 🇪🇬

5 documents

1 / 29

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Assignment 1 Elementary Programming
a) Some Websites impose certain rules for passwords. Write a Java program that checks whether a string is
a valid password. Suppose the password rule is as follows:
A password must have at least eight characters.
A password consists of only letters and digits.
A password must contain at least two digits.
your program prompts the user to enter a password and displays "valid password" if the rule is followed
or "invalid password" otherwise.
import java.util.Scanner;
public class TestPassword {
public static boolean isValidPassword(String pwd) {
if (pwd.length() < 8)
return false;
int digitCount = 0;
for (int i = 0; i < pwd.length(); i++) {
char ch = pwd.charAt(i);
if (Character.isDigit(ch))
digitCount++;
else if (!Character.isLetter(ch))
return false;
// if not also a letter-> return false
}
return digitCount >= 2 ? true : false;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please Enter a Password: ");
String pwd = input.next();
//nextLine()
boolean isValid = isValidPassword(pwd);
System.out.println(isValid ? "valid password" : "invalid password");
}
}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download Java oop assignments questions and answers and more Assignments Java Programming in PDF only on Docsity!

Assignment 1 – Elementary Programming

a) Some Websites impose certain rules for passwords. Write a Java program that checks whether a string is

a valid password. Suppose the password rule is as follows:

  • A password must have at least eight characters.
  • A password consists of only letters and digits.
  • A password must contain at least two digits.

your program prompts the user to enter a password and displays "valid password" if the rule is followed

or "invalid password" otherwise.

import java.util.Scanner;

public class TestPassword {

public static boolean isValidPassword(String pwd) {

if (pwd.length() < 8 )

return false;

int digitCount = 0 ;

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

char ch = pwd.charAt(i);

if (Character.isDigit(ch))

digitCount++;

else if (!Character.isLetter(ch))

return false; // if not also a letter-> return false

return digitCount >= 2? true : false;

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Please Enter a Password: ");

String pwd = input.next(); //nextLine()

boolean isValid = isValidPassword(pwd);

System.out.println(isValid? "valid password" : "invalid password");

b) Write a Java program that displays a multiplication table.

public class MulTableFormatted { public System static.out void.println main(("String\n\t 1 [] args) 2 3 { 4 5 6 7 8 9 10"); System.out.println("--------------------------------------------"); for (int i = 1 ; i <= 10 ; i++) { System.out.print(i + "\t|"); for ( Systemint j (^) .=out 1 ;. (^) printj <= (^) (i 10 ;* jj++ +) "\t ");

System.out.print("\n"); } } }

Assignment 2 – cont’d Elementary Programming

d) Write a program that computes weekly hours for each employee. Use a two-dimensional array. Each row

records an employee’s seven-day work hours with seven columns.

e) Write a java application program to demonstrate the use of the following three methods:

• a method to find the greatest common divisor of given two numbers,

• a method to find the sum of the series: sum = 0.07 + 0.14 + 0.21 + … + 2.

• a recursive method for computing a Fibonacci number fib(n), given index n.

▪ fib(0) = 0;

▪ fib(1) = 1;

▪ fib(n) = fib(n-2) + fib(n-1); n >= 2.

public class WeeklyHours { public static void main(String[] args) { double[][] weeklyHours = { { 1 , 1 , 1 , 1 , 1 , 1 , 1 }, { 5 , 5 , 5 , 5 , 5 , 5 , 5 }, }; // each^ {^3 row,^3 ,represents^3 ,^3 ,^3 ,^3 individual,^3 }, employee's 7 - day work hours for (int i = 0 ; i < weeklyHours.length; i++) { double totalHours = 0 ; for (int j = 0 ; j < weeklyHours[i].length; j++) System^ totalHours.out.println^ +=^ weeklyHours[i][j];("Employee " + (i + 1 ) + " total working hours = " + totalHours); } } }

public class Gcd_Series_Fib { public static int gcd(int a, int b) { int gcd = 1 ; // Math.abs() - > gets the absolute value for a & b: for ( ifint (a i %= i 1 ;== i 0 <= && Math b %. absi ==(a) 0 )&& i <= Math.abs(b); i++) gcd = i; return gcd; } public double static sum double = 0 ; seriesSum(double start, double end, double inc) { for (double i = start; i <= end; i += inc) sum += i; return sum; } public if static(n == 0 int || fibn ==(int 1 ) n) { return n; else return fib(n - 2 ) + fib(n - 1 ); } public static void main(String[] args) { System.out.println("GCD(4,6): " + gcd( 4 , 6 )); System.out.println("Sum of [0.07 + 0.14 +...+ 2.1]: " + seriesSum(0.07, 2.1, 0.07)); System.out.println("Fib(1): " + fib( 1 )); System.out.println("Fib(4): " + fib( 4 )); }^ }

Assignment 3 – OOP: Classes

a) Explain the object-oriented concepts of: object, class, and method overloading. Design and implement a

java class named Circle. The class contains:

• Two private double data fields x, and y that specify the center of the circle.

• A private double data field radius.

• A no-arg constructor that creates a circle (0,0) for (x, y) and 1 for radius.

• A constructor that creates a circle a with specified x, y, and radius.

• Three get methods for data fields x, y, and radius, respectively.

• Three set methods for data fields x, y, and radius, respectively.

• A method getArea() that returns the area of the circle.

• A method getPerimeter() that returns the perimeter of the circle.

• A method contains(double x1, double y1) that returns false if the specified point (x1, y1) is outside

the circle.

• The method print() to print the circle data of an existing object.

Write a test class that creates two objects of the Circle class one of them is default and demonstrates

the use of all the Circle class methods.

Answer

• An object represents an entity in the real world that can be distinctly identified. For example, a student,

a desk, a circle, a button, and even a loan can all be viewed as objects.

• Classes: are constructs that define objects of the same type.

• Method Overloading is when a method is defined more than one time with a different argument or

parameters.

TestCircle.java (test class):

Notes about the “contain” method:

//5:test class that include the main method: public class TestCircle { public static void main(String[] args) { // ==> 1:Create object from the class Circle c1 = new Circle(); // non-arg Circle c2 = new Circle( 3 , 3 , 5 ); // arg // ==> 2:use the object to demonstrate the methods c1.setRadius( 4 ); System.out.println("c1 area: "+c1.getArea()); System.out.println("c1 Perimeter: "+c1.getPerimeter()); c2.setX( 0 ); c2.setY( 0 ); if(c2.contains( 1 , 2 )){ System.out.println("C1 contains the point (1,2)"); } System.out.println("c2 X:"+c2.getX()); System System..outout..printlnprintln(("c2"c2 y:"radius:"+c2.getY+c2());.getRadius()); c2.print(); } }

b) Define and implement a java Time class. Each object of this class represents certain time of the day. The

hours, minutes, seconds, are stored as integer numbers. The class includes a constructor, the method

normalize() that convert an object time such that its elements become in the correct range

( 0 < hr <24, 0<min<60, 0<sec<60), the method advance(int h, int m, int s) to advance the current time

of an existing object, the method reset(int h, int m, int s) to reset the time of an existing object, and the

method print(). Write a java application program to demonstrate this class; enter the time data as

parameters to the main() method.

Time.java

TestTime.java

public private class intTime hours, { minutes, seconds;

Time(int h, int m, int s) { hours = h; minutes = m; seconds = s; }^ normalize(); private void normalize() { if (seconds >= 60 ) { minutes += seconds / 60 ; }^ seconds^ =^ seconds^ %^60 ; if (minutes >= 60 ) { hours += minutes / 60 ; minutes = minutes % 60 ; } if (hours >= 24 ) }^ hours^ =^ hours^ %^24 ; public void advance(int h, int m, int s) { hours += h; minutes += m; seconds normalize +=(); s; } public void reset(int h, int m, int s) { hours = h; minutes = m; seconds normalize = (^) ();s; } public void print() { System.out.println(hours + ":" + minutes + ":" + seconds); }^ }

public class TestTime { public static void main(String[] args) { Time t = new Time( 20 , 10 , 61 ); System.out.print("Time = "); t.print(); System t.advance.out(. 2 print, 30 ,( "Time 20 ); after Advance = "); t.print(); t.reset( 0 , 0 , 1 ); System.out.print("Time after reset = "); }^ t.print(); }

ComplexNumber.java

TestComplex.java

public private class finalComplexNumber double x (^) ;{ // the real part private final double y; // the imaginary part ComplexNumber(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public double magnitude() { return Math.sqrt(Math.pow(x, 2 ) + Math.pow(y, 2 )); } public ComplexNumber add(ComplexNumber num) { double real = x + num.getX(); double imag = y + num.getY(); return new ComplexNumber(real, imag); } public ComplexNumber conjugate() { return new ComplexNumber(x, - y); } public ComplexNumber multiply(ComplexNumber num) { // although "num.y" is private, it works here because // it's used inside the same class name (ComplexNumber) // recommended - > use num.getY() instead double double realimag == xx ** numnum..xy - + yy ** numnum..yx;; return new ComplexNumber(real, imag); } public boolean equals(ComplexNumber num) { return (x == num.x) && (y == num.y); } @ publicOverride String toString() { // overriding toString method (used when object is required as string) if (y == 0 ) return x + ""; if (x == 0 ) return y + "i"; return x + " + " + y + "i"; } }

public class TestComplex { public static void main(String[] args) { ComplexNumber a = new ComplexNumber(5.0, 6.0); ComplexNumber b = new ComplexNumber(-3.0, 4.0); System.out.println("a = " + a); System.out.println("b = " + b); ComplexNumber c = a.add(b); System.out.println("a + b =" + c); System.out.println("a * b =" + a.multiply(b)); System System..outout..printlnprintln(("magnitude"conjugate ofof aa == "" ++ aa..magnitudeconjugate());()); } }

Assignment 5 – OOP: Inheritance

a) Explain the object-oriented concepts of: inheritance, method overriding, and polymorphism. Design and

implement a java class named VEHICLE and its two subclasses CAR and TRUCK.

• A vehicle has vehicleId , price , and plateNumber. A car has numberOfPassengers and

maxSpeed.

• A truck has tonnage and numberOfAxles.

• Each of these three classes should have a constructor and print() method to display its data;

override the superclass methods in each subclass.. Override the toString method in each class to

display the class name and vehicle's plate number. Write a test class that creates a car object, truck

object, and invokes their print() and toString() methods.

Answer

• Inheritance : is the ability in object-oriented programming to derive new classes from existing classes.

• Method Overloading is when a method is defined more than one time with a different argument or

parameters.

• Polymorphism is the ability of an object to take on many forms. The most common use of

polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

“Vehicle.java” Class:

“Car.java” Class:

class Vehicle { protected String vehicleId, plateNumber; protected double price; public Vehicle(String vehicleId, double price, String plateNumber) { this.vehicleId = vehicleId; this.price = price; this.plateNumber = plateNumber; } public void print() { System.out.println("vehicleId: " + vehicleId); System.out.println("price: " + price); System.out.println("plateNumber: " + plateNumber); } public String toString() { return "ClassName: Vehicle, plateNumber: " + plateNumber; } }

class private Car extends int numberOfPassengers, Vehicle { maxSpeed;

public Car(String vehicleId, double price, String plateNumber, int numberOfPassengers, int maxSpeed) { super(vehicleId, price, plateNumber); this.numberOfPassengers = numberOfPassengers; this.maxSpeed = maxSpeed; } public void print() { super.print(); System.out.println("numberOfPassengers: " + numberOfPassengers); System.out.println("maxSpeed: " + maxSpeed); } public String toString() { return "ClassName: Car, plateNumber: " + plateNumber; } }

b) Write the code of a java class named Patient and its two subclasses Inpatient and Outpatient. A patient

has a name , address , phone , and admit-Date. An inpatient has a room-number , bed-number , and

discharge-date. An outpatient has checkBack-date. Each of these three classes should have a constructor

and a print() method to display its data; override the superclass methods in each subclass. Override the

toString method in each class to display the class name and patient's name. Write a test class that creates

an inpatient object, outpatient object, and invokes their print() and toString() methods.

“Patient.java” Class:

“InPatient.java” Class:

public class Patient { protected String name, address, phone, admitDate; public this Patient.name (=String name; name, String address, String phone, String admitDate) { this.address = address; this.phone = phone; this.admitDate = admitDate; } public void print() { System.out.println("Name: " + this.name); System.out.println("Address: " + this.address); System.out.println("Phone: " + this.phone); System.out.println("AdmitDate: " + this.admitDate); } public String toString() { return "ClassName: Patient, PatientName: " + name; } }

public class Inpatient extends Patient { private int roomNumber, bedNumber; private String dischargeDate; public Inpatient(String name, String address, String phone, String admitDate, int roomNumber, int bedNumber, String dischargeDate) { super(name, address, phone, admitDate); this.roomNumber = roomNumber; this.bedNumber = bedNumber; }^ this.dischargeDate^ =^ dischargeDate; public void print(){ super.print(); System.out.println("RoomNumber: " + this.roomNumber); System System..outout..printlnprintln(("BedNumber:"DischargeDate: " + this" + .thisbedNumber.dischargeDate); ); } public String toString(){ return "ClassName: Inpatient, PatientName: " + name; } }

“OutPatient.java” Class:

“TestPatient.java” Class:

public class Outpatient extends Patient { private String checkBackDate; public Outpatient(String name, String address, String phone, String admitDate, String checkBackDate) { super(name, address, phone, admitDate); }^ this.checkBackDate^ =^ checkBackDate; public void print(){ super.print(); System.out.println("CheckBackDate: "+this.checkBackDate); } public String toString(){ return "ClassName: Outpatient, PatientName: " + name; } }

public public class static TestPatients void main {(String[] args) { Inpatient inPatient = new Inpatient("Ahmed","Cairo","0109999999","7/10/2022", 1 , 2 ,"7/12/2022"); Outpatient outPatient = new Outpatient("Ali","Cairo","0108888888","21/10/2022","30/10/2022"); System.out.println(inPatient); System.out.println("------------------"); inPatient System.out.print.println();("\n"); System.out.println(outPatient); System.out.println("------------------"); outPatient.print(); } }

“Circle” Class:

“Cube” Class:

“Cuboid” Class:

public class Circle extends Two_Dimensional { private double radius; public Circle(double r) { radius = r; } public void print() { System.out.println("2-D Shape: (Circle)"); } public return double Math area.PI() * {Math.pow(radius, 2 ); } public double perimeter() { return 2 * Math.PI * radius; } }

public class Cube extends Three_Dimensional { private double edge; public Cube(double edge) { this.edge = edge; } public double area() { return 6 * Math.pow(edge, 2 ); } public void print() { }^ System.out.println("3-D^ Shape:^ (Cube)"); public double volume() { return Math.pow(edge, 3 ); } }

public class Cuboid extends Three_Dimensional {

private double l, w, h;

public Cuboid(double l, double w, double h) {

this.l = l;

this.w = w;

this.h = h;

public void print() { System.out.println("3-D Shape: (Cuboid)"); }

public double area() { return 2 * (w * l + h * l + h * w); }

public double volume() { return l * w * h; }

“TestShape” Class:

public class TestShape {

public static void main(String[] args) {

Two_Dimensional circle = new Circle( 2 );

circle.print();

System.out.println("Area = " + circle.area());

System.out.println("Perimeter = " + circle.perimeter());

System.out.println();

Two_Dimensional square = new Square( 2 , 3 );

square.print();

System.out.println("Area = " + square.area());

System.out.println("Perimeter = " + square.perimeter());

System.out.println();

Three_Dimensional cube = new Cube( 2 );

cube.print();

System.out.println("Area = " + cube.area());

System.out.println("Volume = " + cube.volume());

System.out.println();

Three_Dimensional cuboid = new Cuboid( 2 , 4 , 6 );

cuboid.print();

System.out.println("Area = " + cuboid.area());

System.out.println("Volume = " + cuboid.volume());

Drawing Graphics in Panels

b) Write an object-oriented java program that uses a pie chart to display the percentages of blood types for a

group of people represented by type A, type B, type AB, and type O. Suppose type A takes 20% and is

displayed in green, type B takes 25% and is displayed in red, type AB takes 15% and is displayed in

orange, and type O takes 40% and is displayed in blue.

1. Create a panel subclass (Blood-Panel) to draw the pie chart.

2. Create a frame subclass (Blood-Frame) that adds an instance of the panel to the frame and a

main() method to display the pie chart.

TestBloodType.java:

import javax.swing.; import java.awt.; class Slice { double value; Color color; String label; public Slice(String label, double value, Color color) { this.label = label; this.value = value; this.color = color; } } class BloodPanel extends JPanel { Slice[] slices = { new Slice("A: 20%", 20 , Color.GREEN), new Slice("B: 25%", 25 , Color.RED), new Slice("AB: 15%", 15 , Color.ORANGE), new Slice("O: 40%", 40 , Color.BLUE) }; public void paintComponent(Graphics g) { super.paintComponent(g); // ==> 1. getting panel width, height, & center: int panelWidth = getWidth(); int panelHeight = getHeight(); int int panelCenterXpanelCenterY == panelWidthpanelHeight / / 2 ; 2 ;

// ==> 2. calculating the diameter (80% of panel size), & the radius: int diameter = (int) (Math.min(panelWidth, panelHeight) * 0.80); int radius = (int) (diameter / 2 ); int x = panelCenterX - radius; // "top left" corner of arc int y = panelCenterY - radius; // "top left" corner of arc // ==> 3. drawing arcs: double currentPercentage = 0.0; double totalPercentage = 100 ; // 100% (percentage of all slices) for (int i = 0 ; i < slices.length; i++) { int startAngle = (int) (currentPercentage * 360 / totalPercentage); int arcAngle = (int) (slices[i].value * 360 / totalPercentage); g.setColor(slices[i].color); g.fillArc(x, y, diameter, diameter, startAngle, arcAngle); // (x, y, w, h, startAngle, arcAngle) // 4. drawing arcs labels: g.setColor(Color.BLACK); // Black Text Label double arcCenterDeg = startAngle + (arcAngle / 2 ); //^ double https://en.wikipedia.org/wiki/Polar_coordinate_system#Converting_between_polar_and_Cartesian_coordinates^ arcCenterRad^ =^ arcCenterDeg^ *^ (Math.PI^ /^180 );^ //^ convert^ from^ deg^ to^ rad int labelX = (int) (radius * Math.cos(arcCenterRad)); // convert polar to the Cartesian coordinates int labelY = (int) (radius * Math.sin(arcCenterRad)); g.drawString(slices[i].label, panelCenterX + labelX, panelCenterY - labelY); currentPercentage += slices[i].value; } }^ }

Output:

public class TestBloodType extends JFrame { public TestBloodType() { getContentPane().add(new BloodPanel()); } public JFrame static frame void = new main TestBloodType(String[] args)(); { frame.setSize( 400 , 400 ); frame.setTitle("Blood Types"); frame.setVisible(true); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); } }