0% found this document useful (0 votes)
27 views39 pages

Mahad Oop 2

Uploaded by

mahad7938khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views39 pages

Mahad Oop 2

Uploaded by

mahad7938khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Lab Assignment 2

SUBJECT: OBJECT ORIENTED


PROGRAMMING

SUBMITTED TO:
Miss Arubah Hussain

SUBMITTED BY:
Mahad Khan

REGISTRATION NO:
FA23-BCS-003
Question 1:
class BeerSong {

int bottle;

public BeerSong (int bottle){

if (bottle<0){

System.out.println("Zero Bottles of Beer On The Wall");

else if (bottle >99){

this.bottle=99;

else{

this.bottle=bottle;

public void printSong(){

for ( int i=bottle;i>=0;i--){

System.out.println(convertNumberToWords(i)+" Bottles of the Beer on the


wall");

System.out.println(convertNumberToWords(i)+" Bottles of the beer");

System.out.println(" take one down pass it round");

System.out.println(convertNumberToWords(i-1)+" bottle on the wall");

}
}

private String convertNumberToWords(int n) {

String[] belowTwenty = {"Zero", "One", "Two", "Three", "Four", "Five", "Six",


"Seven", "Eight", "Nine", "Ten",

"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",


"Seventeen", "Eighteen", "Nineteen"};

String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety"};

if (n < 20) {

return belowTwenty[n]; // Direct lookup for numbers less than 20

} else {

int tenVal = n / 10; // Get the tens place

int unitVal = n % 10; // Get the unit place

if (unitVal == 0) {

return tens[tenVal]; // If the unit is 0, return only the tens word

} else {

return tens[tenVal] + "-" + belowTwenty[unitVal]; // Combine tens and unit


for numbers like "Ninety-nine"

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

BeerSong b = new BeerSong(99);

b.printSong();

Question 2:
package com.mycompany.rational;
public class Rational {
private int numerator;
private int denominator;

public Rational(int numerator, int denominator) {


this.numerator = numerator;
setDenominator(denominator);
}

public void setNumerator(int numerator) {


this.numerator = numerator;
}
public void setDenominator(int denominator) {
if (denominator != 0) {
this.denominator = denominator;
} else {
throw new IllegalArgumentException("Denominator cannot be zero.");
}
}
// Method to reduce fraction
public void reduce() {
int gcd = gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
// Greatest Common Divisor (GCD)
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
public static void main(String[] args) {
Rational fraction = new Rational(20, 60);
System.out.println("Before Reduction: " + fraction);
fraction.reduce();
System.out.println("After Reduction: " + fraction);
}
}

Question 4:
package blogentry;

import java.util.Date;

import java.text.SimpleDateFormat;
public class BlogEntry {

// Instance variables

private String username;

private String text;

private Date date;

// Constructor to initialize the username, text, and date of the blog


entry

public BlogEntry(String username, String text) {

this.username = username;

this.text = text;

this.date = new Date(); // Sets the current date and time

// Method to display all instance variables (username, text, date)

public void displayEntry() {

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-


MM-dd HH:mm:ss");

System.out.println("Username: " + username);


System.out.println("Date: " + dateFormat.format(date));

System.out.println("Entry: " + text);

// Method to get the first 10 words from the text (or the entire text if
it's less than 10 words)

public String getSummary() {

String[] words = text.split("\\s+"); // Split the text into words by


spaces

if (words.length <= 10) {

return text; // Return the entire text if it has 10 words or less

} else {

StringBuilder summary = new StringBuilder();

for (int i = 0; i < 10; i++) {

summary.append(words[i]).append(" ");

return summary.toString().trim() + "..."; // Add "..." at the end


for longer summaries

}
// Main method to test the BlogEntry class

public static void main(String[] args) {

// Create a BlogEntry object

BlogEntry entry = new BlogEntry("JohnDoe", "This is a sample blog


entry that demonstrates the use of the BlogEntry class in Java.");

// Display the full blog entry

System.out.println("Displaying full entry:");

entry.displayEntry();

// Display the summary of the blog entry

System.out.println("\nDisplaying summary:");

System.out.println(entry.getSummary());

Question 5:
class Counter {

private int count; // Variable to store the count value

// Constructor to initialize the counter to 0


public Counter() {

this.count = 0;

// Method to reset the counter to 0

public void reset() {

this.count = 0;

// Method to increase the counter by 1

public void increase() {

count++;

// Method to decrease the counter by 1 but not below 0

public void decrease() {

if (count > 0) {

count--;

} else {

System.out.println("Count is already zero, can't go negative.");


}

// Accessor method to return the current count

public int getCount() {

return count;

// Method to print the current count value

public void display() {

System.out.println("Current count is: " + count);

// Override toString method to provide a string representation of the


object

@Override

public String toString() {

return "Counter [count=" + count + "]";

}
// Override equals method to compare two Counter objects

@Override

public boolean equals(Object obj) {

if (this == obj) return true;

if (obj == null || getClass() != obj.getClass()) return false;

Counter counter = (Counter) obj;

return count == counter.count;

// Main method to test the class methods

public static void main(String[] args) {

Counter counter1 = new Counter();

Counter counter2 = new Counter();

counter1.increase();

counter1.increase();

counter1.display(); // Should display 2

counter1.decrease();

counter1.display(); // Should display 1


System.out.println(counter1); // Should print Counter [count=1]

counter1.reset();

counter1.display(); // Should display 0

// Check if counter1 equals counter2 (both should be 0 at this


point)

System.out.println("Are both counters equal? " +


counter1.equals(counter2)); // Should print true

Question 7:
public class Temperature {

private double temperature;

private char scale;

public Temperature() {

this.temperature = 0.0;

this.scale = 'C';

public Temperature(double temperature) {


this.temperature = temperature;

this.scale = 'C';

public Temperature(double temperature, char scale) {

this.temperature = temperature;

this.scale = Character.toUpperCase(scale);

public double getCelsius() {

if (scale == 'C') {

return round(temperature);

} else {

return round((temperature - 32) * 5.0 / 9.0);

public double getFahrenheit() {

if (scale == 'F') {

return round(temperature);

} else {

return round(temperature * 9.0 / 5.0 + 32);

}
}

public void setTemperature(double temperature) {

this.temperature = temperature;

public void setScale(char scale) {

this.scale = Character.toUpperCase(scale);

public void setTemperature(double temperature, char scale) {

this.temperature = temperature;

this.scale = Character.toUpperCase(scale);

public boolean equals(Temperature other) {

return this.getCelsius() == other.getCelsius();

public boolean isGreaterThan(Temperature other) {

return this.getCelsius() > other.getCelsius();

public boolean isLessThan(Temperature other) {


return this.getCelsius() < other.getCelsius();

@Override

public String toString() {

return String.format("%.1f degrees %s", temperature, scale);

private double round(double value) {

return Math.round(value * 10.0) / 10.0;

public static void main(String[] args) {

Temperature temp1 = new Temperature();

Temperature temp2 = new Temperature(32.0, 'F');

Temperature temp3 = new Temperature(0.0, 'C');

Temperature temp4 = new Temperature(-40.0, 'C');

Temperature temp5 = new Temperature(100.0, 'C');

System.out.println("Temp 1: " + temp1);

System.out.println("Temp 2: " + temp2);

System.out.println("Temp 3: " + temp3);

System.out.println("Temp 4: " + temp4);


System.out.println("Temp 5: " + temp5);

System.out.println("Temp 1 equals Temp 2? " + temp1.equals(temp2));

System.out.println("Temp 4 equals Temp 2? " + temp4.equals(temp2));

System.out.println("Temp 5 equals 212.0 F? " + temp5.equals(new


Temperature(212.0, 'F')));

System.out.println("Temp 5 is greater than Temp 3? " +


temp5.isGreaterThan(temp3));

System.out.println("Temp 3 is greater than Temp 1? " +


temp3.isGreaterThan(temp1));

System.out.println("Temp 1 is less than Temp 2? " +


temp1.isLessThan(temp2));

System.out.println("Temp 4 is less than Temp 3? " +


temp4.isLessThan(temp3));

Question 8:
import java.util.Scanner;

public class Date {

private int month;

private int day;

private int year;


public Date() {

month = 1; // January

day = 1;

year = 1000;

public Date(int monthInt, int day, int year) {

setDate(monthInt, day, year);

public Date(String monthString, int day, int year) {

setDate(monthString, day, year);

public Date(int year) {

setDate(1, 1, year);
}

public Date(Date aDate) {

if (aDate == null) {

System.out.println("Fatal Error.");

System.exit(0);

this.month = aDate.month;

this.day = aDate.day;

this.year = aDate.year;

public void setDate(int monthInt, int day, int year) {

if (dateOK(monthInt, day, year)) {

this.month = monthInt;

this.day = day;

this.year = year;

} else {
System.out.println("Fatal Error");

System.exit(0);

public void setDate(String monthString, int day, int year) {

int monthInt = monthStringToInt(monthString);

setDate(monthInt, day, year);

public void setYear(int year) {

if (year >= 1000 && year <= 9999) {

this.year = year;

} else {

System.out.println("Fatal Error");

System.exit(0);

}
public void setMonth(int monthNumber) {

if (monthNumber >= 1 && monthNumber <= 12) {

this.month = monthNumber;

} else {

System.out.println("Fatal Error");

System.exit(0);

public void setDay(int day) {

if (day >= 1 && day <= 31) {

this.day = day;

} else {

System.out.println("Fatal Error");

System.exit(0);

(as int)

public int getMonth() {


return month;

public int getDay() {

return day;

public int getYear() {

return year;

public String toString() {

return monthIntToString(month) + " " + day + ", " + year;

private boolean dateOK(int monthInt, int dayInt, int yearInt) {

return (monthInt >= 1 && monthInt <= 12) &&

(dayInt >= 1 && dayInt <= 31) &&

(yearInt >= 1000 && yearInt <= 9999);


}

private boolean dateOK(String monthString, int dayInt, int yearInt)


{

int monthInt = monthStringToInt(monthString);

return dateOK(monthInt, dayInt, yearInt);

private int monthStringToInt(String month) {

switch (month.toLowerCase()) {

case "january": return 1;

case "february": return 2;

case "march": return 3;

case "april": return 4;

case "may": return 5;

case "june": return 6;

case "july": return 7;

case "august": return 8;

case "september": return 9;


case "october": return 10;

case "november": return 11;

case "december": return 12;

default:

System.out.println("Fatal Error");

System.exit(0);

return 0; // Should never reach here

private String monthIntToString(int monthInt) {

switch (monthInt) {

case 1: return "January";

case 2: return "February";

case 3: return "March";

case 4: return "April";

case 5: return "May";

case 6: return "June";

case 7: return "July";


case 8: return "August";

case 9: return "September";

case 10: return "October";

case 11: return "November";

case 12: return "December";

default:

System.out.println("Fatal Error");

System.exit(0);

return "Error"; // Should never reach here

public static void main(String[] args) {

Date date1 = new Date(2, 29, 2020);

System.out.println("Date1: " + date1);

Date date2 = new Date("March", 15, 2021);

System.out.println("Date2: " + date2);

Date date3 = new Date(2022);


System.out.println("Date3: " + date3);

Date date4 = new Date(date1);

System.out.println("Copy of Date1: " + date4);

Question 9:
public class AnimalSpecies {

private String speciesName;

private int population;

private double growthRate;

public AnimalSpecies() {

this.speciesName = "Unknown";

this.population = 0;

this.growthRate = 0.0;

public AnimalSpecies(String speciesName, int population, double growthRate) {

this.speciesName = speciesName;

this.population = population;

this.growthRate = growthRate;

}
public String getSpeciesName() {

return speciesName;

public int getPopulation() {

return population;

public double getGrowthRate() {

return growthRate;

public void setSpeciesName(String speciesName) {

this.speciesName = speciesName;

public void setPopulation(int population) {

this.population = population;

public void setGrowthRate(double growthRate) {

this.growthRate = growthRate;

}
public boolean endangered() {

return growthRate < 0;

@Override

public String toString() {

return String.format("Species: %s, Population: %d, Growth Rate: %.2f%%",


speciesName, population, growthRate);

@Override

public boolean equals(Object obj) {

if (this == obj) return true;

if (obj == null || getClass() != obj.getClass()) return false;

AnimalSpecies other = (AnimalSpecies) obj;

return speciesName.equals(other.speciesName) && population ==


other.population && Double.compare(growthRate, other.growthRate) == 0;

public static void main(String[] args) {

AnimalSpecies species1 = new AnimalSpecies("Tiger", 3200, -2.5);

AnimalSpecies species2 = new AnimalSpecies("Elephant", 60000, 1.2);

AnimalSpecies species3 = new AnimalSpecies("Panda", 1864, 0.0);


AnimalSpecies species4 = new AnimalSpecies("Tiger", 3200, -2.5);

System.out.println(species1);

System.out.println(species2);

System.out.println(species3);

System.out.println("Is " + species1.getSpeciesName() + " endangered? " +


species1.endangered());

System.out.println("Is " + species2.getSpeciesName() + " endangered? " +


species2.endangered());

System.out.println("Is " + species3.getSpeciesName() + " endangered? " +


species3.endangered());

System.out.println("Is species1 equal to species4? " +


species1.equals(species4));

System.out.println("Is species1 equal to species2? " +


species1.equals(species2));

species1.setPopulation(3100);

species1.setGrowthRate(-1.0);

System.out.println("Updated species1: " + species1);

Question 10:
class AnimalSpecies {

private String speciesName;

private int population;

private double growthRate;

public AnimalSpecies(String speciesName, int population, double


growthRate) {

this.speciesName = speciesName;

this.population = population;

this.growthRate = growthRate;

public String getSpeciesName() {

return speciesName;

public void setSpeciesName(String speciesName) {

this.speciesName = speciesName;

}
public int getPopulation() {

return population;

public void setPopulation(int population) {

this.population = population;

public double getGrowthRate() {

return growthRate;

public void setGrowthRate(double growthRate) {

this.growthRate = growthRate;

public boolean isEndangered() {

return growthRate < 0;

}
@Override

public String toString() {

return "AnimalSpecies{" +

"speciesName='" + speciesName + '\'' +

", population=" + population +

", growthRate=" + growthRate +

'}';

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (o == null || getClass() != o.getClass()) return false;

AnimalSpecies that = (AnimalSpecies) o;

return population == that.population &&


Double.compare(that.growthRate, growthRate) == 0 &&
Objects.equals(speciesName, that.speciesName);

public class AnimalSpeciesTest {


public static void main(String[] args) {

AnimalSpecies tiger = new AnimalSpecies("Tiger", 5000, -2.5);

AnimalSpecies elephant = new AnimalSpecies("Elephant", 10000,


1.5);

System.out.println(tiger.isEndangered()); // Output: true

System.out.println(elephant.isEndangered()); // Output: false

System.out.println(tiger.toString());

System.out.println(elephant.toString());

Question 11:
public class Pizza {

private String size;

private int cheeseToppings;

private int pepperoniToppings;

private int hamToppings;

public Pizza(String size, int cheeseToppings, int pepperoniToppings, int


hamToppings) {
setSize(size);

this.cheeseToppings = cheeseToppings;

this.pepperoniToppings = pepperoniToppings;

this.hamToppings = hamToppings;

public void setSize(String size) {

if (size.equalsIgnoreCase("small") || size.equalsIgnoreCase("medium") ||
size.equalsIgnoreCase("large")) {

this.size = size;

} else {

throw new IllegalArgumentException("Size must be small, medium, or


large.");

public String getSize() {

return size;

public int getCheeseToppings() {

return cheeseToppings;

}
public int getPepperoniToppings() {

return pepperoniToppings;

public int getHamToppings() {

return hamToppings;

public double calcCost() {

double baseCost;

switch (size.toLowerCase()) {

case "small":

baseCost = 10.0;

break;

case "medium":

baseCost = 12.0;

break;

case "large":

baseCost = 14.0;

break;

default:
baseCost = 0.0;

return baseCost + 2 * (cheeseToppings + pepperoniToppings + hamToppings);

public String getDescription() {

return String.format("Size: %s, Cheese Toppings: %d, Pepperoni Toppings:


%d, Ham Toppings: %d, Total Cost: $%.2f",

size, cheeseToppings, pepperoniToppings, hamToppings, calcCost());

public static void main(String[] args) {

Pizza pizza1 = new Pizza("large", 1, 1, 2);

Pizza pizza2 = new Pizza("medium", 2, 0, 1);

Pizza pizza3 = new Pizza("small", 0, 2, 3);

System.out.println(pizza1.getDescription());

System.out.println(pizza2.getDescription());

System.out.println(pizza3.getDescription());

Question 12:
package com.mycompany.pizza;

public class PizzaOrder {

private Pizza pizza1;

private Pizza pizza2;

private Pizza pizza3;

private int numPizzas;

public void setNumPizzas(int numPizzas) {

if (numPizzas < 1 || numPizzas > 3) {

throw new IllegalArgumentException("Number of pizzas must be


between 1 and 3.");

this.numPizzas = numPizzas;

// Methods to set pizzas

public void setPizza1(Pizza pizza1) {

this.pizza1 = pizza1;

public void setPizza2(Pizza pizza2) {

this.pizza2 = pizza2;
}

public void setPizza3(Pizza pizza3) {

this.pizza3 = pizza3;

// Method to calculate total cost

public double calcTotal() {

double total = 0;

if (numPizzas >= 1) total += pizza1.calcCost();

if (numPizzas >= 2) total += pizza2.calcCost();

if (numPizzas == 3) total += pizza3.calcCost();

return total;

// Main method to test the PizzaOrder class

public static void main(String[] args) {

Pizza pizza1 = new Pizza("Large", 2, 3, 1);

Pizza pizza2 = new Pizza("Medium", 1, 0, 2);

Pizza pizza3 = new Pizza("Small", 0, 1, 0);

PizzaOrder order = new PizzaOrder();

order.setNumPizzas(3);

order.setPizza1(pizza1);
order.setPizza2(pizza2);

order.setPizza3(pizza3);

double total = order.calcTotal();

System.out.println("Total order cost: $" + total);

public class PizzaTest {

public static void main(String[] args) {

Pizza pizza1 = new Pizza("Large", 2, 3, 1); // Large pizza with 2


cheese, 3 pepperoni, and 1 ham

Pizza pizza2 = new Pizza("Medium", 1, 0, 2); // Medium pizza with 1


cheese, 0 pepperoni, and 2 ham

Pizza pizza3 = new Pizza("Small", 0, 1, 0); // Small pizza with 0


cheese, 1 pepperoni, and 0 ham

PizzaOrder order = new PizzaOrder();

order.setNumPizzas(3);

order.setPizza1(pizza1);
order.setPizza2(pizza2);

order.setPizza3(pizza3);

System.out.println(pizza1.getDescription());

System.out.println(pizza2.getDescription());

System.out.println(pizza3.getDescription());

// Calculate the total cost

double total = order.calcTotal();

System.out.println("Total order cost: $" + total);

You might also like