0% found this document useful (0 votes)
2 views

OOP Assignment 02

The document contains a series of Java programming assignments that cover various concepts such as class creation, method overloading, interface implementation, and data handling. Each assignment includes code examples and explanations for tasks like creating a math class, managing room data, finding the largest number, and implementing an invoice system. The document serves as a comprehensive guide for practicing Java programming skills.

Uploaded by

greenlouisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

OOP Assignment 02

The document contains a series of Java programming assignments that cover various concepts such as class creation, method overloading, interface implementation, and data handling. Each assignment includes code examples and explanations for tasks like creating a math class, managing room data, finding the largest number, and implementing an invoice system. The document serves as a comprehensive guide for practicing Java programming skills.

Uploaded by

greenlouisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

OOP Assignment 02

(Java Practice Problem)


Jahid Anuar Ananda

1.
Create a Class MyMath. Within this class write three overloaded methods add(). The First Method
takes two integer parameter , add them and return the result. The second method takes an
integer number and return the sum of the series from 1 to the number. The third method takes
one integer and one floating value and work as type conversion (widing and narrowing).

public class MyMath {


public int add(int a, int b)
{
int result;
result = a + b;
return result;
}
public int add(int n)
{
int i, sum = 0;
for(i=1; i<=n; i++)
{
sum = sum + i;
}
return sum;
}
public void add(int a, float b)
{
float c = a;
int d = (int)b;
float e = c+d;
System.out.println("Upcasting/Widing result = "+c);
System.out.println("Downcasting/Narrowing result = "+d);
System.out.println("Addition result After widing and narrowing = "+e);
}

public static void main(String[] args) {


MyMath obj = new MyMath();
int Method1 = obj.add(100,200);
int Method2 = obj.add(10);
System.out.println("Two integer value addition = "+Method1);
System.out.println("Addition of n value = "+Method2);
obj.add(10, (float) 10.5);
}
}
[Output 01]

2.
Write a program to create a room class, the attributes of this class is roomno, roomtype,
roomarea and ACmachine. In this class the member functions are setdata and displaydata.

public class Room {


int roomno;
String roomtype;
double roomarea;
boolean ACmachine;
public void SetData(int roomno,String roomtype,double roomarea,boolean ACmachine)
{
this.roomno = roomno;
this.roomtype = roomtype;
this.roomarea = roomarea;
this.ACmachine = ACmachine;
}
public void DisplayData()
{
System.out.println("RoomNo = "+roomno+" Roomtype = "+roomtype+" RoomArea = "+roomarea+"
ACmachine = "+ACmachine);
}
public static void main(String[] args) {
Room obj = new Room();
obj.SetData(105, "XYZ", 5000, true);
obj.DisplayData();
}
}
[Output 02]
3.
Write a program to create interface named test. In this interface the member function is square.
Implement this interface in arithmetic class. Create one new class called ToTestInt in this class
use the object of arithmetic class.

public interface Test {


public abstract void square();
}

public class Arithmetic implements Test {


public void square(int n)
{
System.out.println("The square result is = "+n*n);
}
}

public class TestInt {


Arithmetic obj = new Arithmetic();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int a = sc.nextInt();
obj.square(a);
}

[Output 03]
4.
The process of finding the largest value (i.e., the maximum of a group of values) is used frequently
in computer applications. For example, a program that determines the winner of a sales contest
would input the number of units sold by each sales person. The sales person who sells the most
units wins the contest. Write a Java application that inputs a series of 10 integers and determines
and prints the largest integer. Your program should use at least the following three variables: a.
counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and
to determine when all 10 numbers have been processed). b. number: The integer most recently
input by the user. c. largest: The largest number found so far.

public class LargestNumberFinding {


public static void main(String[] args) {
int counter = 1,number,largest = 0;
Scanner sc = new Scanner(System.in);
while(counter<=10)
{
System.out.println("Enter the number "+counter);
number = sc.nextInt();
counter++;
if(number>largest)
{
largest = number;
}
}
System.out.println("Largest number is = "+largest);
}
}
[Output 04]
5.
Modify class Account (in the example) to provide a method called debit that withdraws money froman
Account. Ensure that the debit amount does not exceed the Account’s balance. If it does, the balance
should be left unchanged and the method should print a message indicating ―Debit amount exceeded
account balance. Modify class AccountTest (in the example) to test method debit.

public class Account {


private double balance;
public Account(double initialBalance)
{
if (initialBalance > 0.0) balance=initialBalance;
}
public void credit(double amount)
{
balance=balance+amount;
}
public void debit(double amount)
{
balance=balance-amount;
}
public double getBalance()
{
return balance;
}
}

public class Account {


private double balance;
public Account(double initialBalance)
{
if (initialBalance > 0.0)
balance=initialBalance;
}
public void credit(double amount)
{
balance=balance+amount;
}
public void debit(double amount)
{
if(balance>amount)
{
balance=balance-amount;
}
else
System.out.println("Debit amount exceeded amount balance");
}
public double getBalance()
{
return balance;
}
}
public class AccountTest {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
Account obj = new Account(5000);

System.out.println("Initial balance = "+obj.getBalance());

System.out.println("Input the credit balance");


double crb = sc.nextDouble();
obj.credit(crb);
System.out.println("Balance after credit = "+obj.getBalance());

System.out.println("Input the debit balance");


double dr = sc.nextDouble();
obj.debit(dr);
System.out.println("Remaining balance = "+obj.getBalance());

}
}
[Output 05]
6.
Create a class called Employee that includes three pieces of information as instance variables—
a first name (typeString), a last name (typeString) and a monthly salary (double). Your class should
have a constructor that initializes the three instance variables. Provide a set and a get method
for each instance variable. If the monthly salary is not positive, set it to 0.0. Write a test
application named EmployeeTest that demonstrates class Employee’s capabilities. Create two
Employee objects and display each object’s yearly salary. Then give each Employee a 10% raise
and display each Employee’s yearly salary again

public class Employee {


private String first_name;
private String last_name;
private double monthly_salary;
Employee(String first,String last, double salary)
{
first_name = first;
last_name = last;
if(salary<0.0)
{
monthly_salary = 0.0;
}
else
{
monthly_salary = salary;
}
}
public void SetFirstName(String fname)
{
first_name = fname;
}

public void SetLasttName(String lname)


{
last_name = lname;
}
public void SetSalary(double salary)
{
if(salary<0.0)
{
monthly_salary = 0.0;
}
else
{
monthly_salary = salary;
}
}
public String GetFirstName()
{
return first_name;
}
public String GetLasttName()
{
return last_name;
}
public double GetSalary()
{
return monthly_salary;
}
}
public class EmployeeTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Employee obj1 = new Employee("Kamal","Uddin",50000.0);
Employee obj2 = new Employee("Aminul","Islam",-40000.0);

System.out.println("Yearly salary of "+obj1.GetFirstName()+" "+obj1.GetLasttName()+" =


"+obj1.GetSalary()*12);
System.out.println("Yearly salary of "+obj2.GetFirstName()+" "+obj2.GetLasttName()+" =
"+obj2.GetSalary()*12);

double incsalary1 = obj1.GetSalary()+(obj1.GetSalary()*10/100);


System.out.println("After 10% increased yearly salary of "+obj1.GetFirstName()+" "+obj1.GetLasttName()+"
= "+incsalary1*12);

double incsalary2 = obj2.GetSalary()+(obj2.GetSalary()*10/100);


System.out.println("After 10% increased yearly salary of "+obj2.GetFirstName()+" "+obj2.GetLasttName()+"
= "+incsalary2*12);
}
}

[Output 06]
7.
Create a class called Date that includes three pieces of information as instance variables—a
month (typeint), a day (typeint) and a year (typeint). Your class should have a constructor that
initializes the three instance variables and assumes that the values provided are correct. Provide
a set and a get method for each instance variable. Provide a method displayDate that displays
the month, day and year separated by forward slashes(/). Write a test application named
DateTest that demonstrates classDate’s capabilities.

public class Date {


private int month;
private int day;
private int year;

Date(int month,int day,int year)


{
if(month>12 || day>31 || (year<1922||year>2122))
{
month = 0;
day = 0;
year = 0;
}
else
{
this.month = month;
this.day = day;
this.year = year;
}

public void SetMonth(int month)


{
if(month>12)
{
month = 0;
}
else
{
this.month = month;
}
}
public void SetDay(int day)
{
if(day>31)
{
day = 0;
}
else
{
this.day = day;
}
}
public void SetYear(int year)
{
if((year<1922 || year>2122))
{
year = 0;
}
else
{
this.year = year;
}
}
public int GetMonth()
{
return month;
}
public int GetDay()
{
return day;
}
public int GetYear()
{
return year;
}
public void DisplayDate()
{
System.out.println("The date is(mm/dd/yyyy) = "+GetMonth()+"/"+GetDay()+"/"+GetYear());
}
}
public class DateTest {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter month");
int m = sc.nextInt();
System.out.println("Enter day");
int d = sc.nextInt();
System.out.println("Enter year");
int y = sc.nextInt();
Date obj = new Date(m,d,y);

obj.DisplayDate();
}
}
[Output 07]
8.
Create class SavingsAccount. Usea static variable annualInterestRate to store the annual interest
rate for all account holders. Each object of the class contains a private instance variable
savingsBalance indicating the amount the saver currently has ondeposit. Provide method
calculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12 this interest should be added to savingsBalance. Provide a static
method modifyInterestRate that sets the annualInterestRate to a new value. Write a program to
test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with
balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate
the monthly interest and print the new balances for both savers. Then set the annualInterestRate
to 5%, calculate the next month’s interest and print the new balances for both savers.

public class SavingsAccount {


static private double annualInterestRate;
private double savingBalance;
public SavingsAccount(double savingBalance)
{
this.savingBalance=savingBalance;
}
public double getSavingBalance()
{
return this.savingBalance;
}

public static void modifyInterestRate(double newInterestRate)


{
annualInterestRate=newInterestRate;
}
public void calculateMonthlyInterest()
{
double monthlyI;
monthlyI= (this.savingBalance*annualInterestRate/12);
this.savingBalance+=monthlyI;
}
public static void main(String[] args) {

SavingsAccount saver1, saver2;


saver1 = new SavingsAccount (2000.0);
saver2= new SavingsAccount (3000.0);

SavingsAccount.modifyInterestRate (0.04);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();

System.out.println("For 4% interest rate:\nSaver 1 balance= "+ saver1.getSavingBalance());


System.out.println("Saver 2 balance= "+ saver2.getSavingBalance());

SavingsAccount.modifyInterestRate(0.05);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();

System.out.println("For 5% interest rate:\nSaver 1 balance= "+ saver1.getSavingBalance());


System.out.println("Saver 2 balance= "+ saver2.getSavingBalance());
}
}
[Output 08]
9.
Create a class called Invoice that a hardware store might use to represent an invoice for an item
sold at the store. An Invoice should include four pieces of information as instance variables‐a part
number(type String),a part description(type String),a quantity of the item being purchased (type
int) and a price per item (double). Your class should have a constructor that initializes the four
instance variables. Provide a set and a get method for each instance variable. In addition, provide
a method named getInvoice Amount that calculates the invoice amount (i.e., multiplies the
quantity by the price per item), then returns the amount as a double value. If the quantity is not
positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a
test application named InvoiceTest that demonstrates class Invoice’s capabilities.

public class Invoice {


private String partNumber;
private String description;
private int quantity;
private double price;

Invoice(String partNumber,String description,int quantity,double price)


{
this.partNumber = partNumber;
this.description = description;
if(quantity<0)
{
this.quantity = 0;
}
else
{
this.quantity = quantity;
}
if(price<0.0)
{
this.price = 0.0;
}
else
{
this.price = price;
}
}
public void SetPartNumber(String partNumber)
{
this.partNumber = partNumber;
}
public void SetDescription(String description)
{
this.description = description;
}
public void SetQuantity(int quantity)
{
if(quantity<0)
{
this.quantity = 0;
}
else
{
this.quantity = quantity;
}
}
public void SetPrice(double price)
{
if(price<0.0)
{
this.price = 0.0;
}
else
{
this.price = price;
}
}
public String GetPartNumber()
{
return partNumber;
}
public String GetDescription()
{
return description;
}
public int GetQuantity()
{
return quantity;
}
public double GetPrice()
{
return price;
}

public double GetInvoiceAmount()


{
double InvoiceAmount = GetQuantity()*GetPrice();
return InvoiceAmount;
}

}
public class InvoiceTest {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter part number");
String pn = sc.nextLine();
System.out.println("Enter part description");
String d = sc.nextLine();
System.out.println("Enter quantity");
int q = sc.nextInt();
System.out.println("Enter price");
double p = sc.nextInt();
Invoice obj = new Invoice(pn,d,q,p);

System.out.println("PartNumber "+obj.GetPartNumber()+" description "+obj.GetDescription()


+" quantity "+obj.GetQuantity()+" price per item "+obj.GetPrice());
System.out.println("Invoice amount = "+obj.GetInvoiceAmount());
}
}
[Output 09]
10.
Write a Java program that reads a string from the keyboard, and outputs the string twice in a
row, first all uppercase and next all lowercase. If, for instance, the string “Hello" is given, the
output will be “HELLOhello

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("Input the string");
String a = sc.nextLine();

System.out.println("Output string = "+a.toUpperCase()+a.toLowerCase());


}
}
[Output 10]

You might also like