Subscribe For Free Updates!

We'll not spam mate! We promise.

Friday, 22 December 2017

Write a java program that contains classes Date, Employee and EmployeeTest

QN. (Composition)Write a java program that contains classes Date, Employee and EmployeeTest.
Class Date declares instance variables month, day and year to represent a date. Create a constructor that receives three int parameters for initializing the objects. Provide a toString method to obtain the object’s String representation.
Class Employee has instance variables firstName, lastName, birthDate and hireDate. Members firstName and lastName are references to String objects. Members birthDate and hireDate are references to Date objects. Create Employee constructor that takes four parameters representing the first name, last name, birth date and hire date for initializing the objects. Provide a toString to returns a String containing the employee’s name and the String representations of the two Date objects.
Class EmployeeTest creates two Date objects to represent an Employee’s birthday and hire date, respectively. It creates an Employee’s object and initializes its instance variables by passing to the constructor two Strings (representing the Employee’s first and last names) and two Date objects (representing the birthday and hire date).

Thursday, 21 December 2017

Saving Account To calculate monthly interest

QN. Create a class Saving Account. Use a 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 on deposit.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 capability. Instantiate two savingsAccount objects, saver1 and saver2, with balances of TSh 20,000.00 and TSh 30,000.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.

ANSWER
SavingAccount.java
package savingaccount;

/**
 *
 * @author Eng.Mghase
 * @email mghase.sadick1@gmail.com
 * @contact 
 * @web http://qksoftz.com
 */
public class SavingAccount {

    private static float annuallInterestRate;
    private float savingsBalance;
    private float monthlyInterest;

    public SavingAccount(float savingsBalance) {
        this.savingsBalance = savingsBalance;

    }

    public void calculateMonthlyInterest() {
        this.monthlyInterest = (savingsBalance * annuallInterestRate) / 12;
        System.out.println("The monthly interest is TSh: " + this.monthlyInterest);
    }

    public static void modifyInterestRate(float interestRate) {
        annuallInterestRate = interestRate;
    }

    private void calculateSavings() {
        savingsBalance += this.monthlyInterest;
    }

    public void displaySavings() {
        calculateSavings();
        System.out.println("The total balance is : TSh " + savingsBalance);
    }

}


SavingAccount.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package savingaccount;
/**
 *
 * @author Eng.Mghase
 * @email mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public class TestClass{

    
    public static void main(String[] args) {
      // SavingAccount.annuallInterestRate=0.25;
       
       SavingAccount saver1=new SavingAccount(20000);
        SavingAccount saver2=new SavingAccount(30000);
       
       SavingAccount.modifyInterestRate(4);
		
       saver1.calculateMonthlyInterest();
		saver2.calculateMonthlyInterest();
		saver1.displaySavings();
		saver2.displaySavings();
		
                SavingAccount.modifyInterestRate(5);
		saver1.calculateMonthlyInterest();
		saver2.calculateMonthlyInterest();
		saver1.displaySavings();
		saver2.displaySavings();
          
          
    }
    
}

Monday, 18 December 2017

(Abstraction) Payroll calculations polymorphically.

QN A company pays its employees on a weekly basis. The employees are of four types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, hourly employees are paid by the hour and receive overtime pay (i.e., 1.5 times their hourly salary rate) for all hours worked in excess of 40 hours, commission employees are paid a percentage of their sales and base-salaried-commission-employees receive a base salary plus a percentage of their sales. For the current pay period, the company has decided to reward salaried-commission employees by adding 10% to their base salaries. The company wants you to write an application that performs its payroll calculations polymorphically. Use abstract class Employee to represent the general concept of an employee. The classes that extend Employee are SalariedEmployee, CommissionEmployee and Hourly-Employee. Class BasePlusCommissionEmployee which extends CommissionEmployee represents the last employee type. The figure below illustrated the hierarchy.

ANSWER
Employee.java
package employee;
/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qwkisoft.com
 */
public abstract class Employee {
  private String firstName;
  private String laststName;
   private String socialSecurityNumber;

    public Employee(String firstName, String laststName, String ssn) {
        this.firstName = firstName;
        this.laststName = laststName;
        this.socialSecurityNumber = ssn;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLaststName() {
        return laststName;
    }

    public void setLaststName(String laststName) {
        this.laststName = laststName;
    }

    public String getSocialSecurityNumber() {
        return socialSecurityNumber;
    }

    public void setSocialSecurityNumber(String ssn) {
        this.socialSecurityNumber = ssn;
    }
  
      // abstract method overridden by concrete subclasses        
     public abstract double earnings(); // no implementation here
     // end abstract class Employee
     
         @Override
     public String toString(){
      return String.format("%s %s ssn: %s", getFirstName(),getLaststName(),getSocialSecurityNumber());
}
}
HourlyEmployee .java

package employee;

/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qwkisoft.com
 */
public class HourlyEmployee extends Employee{
  private double wage; //wage per hour
  private double hours;// hours worked for week


    public HourlyEmployee(String firstName, String laststName, String ssn,double hours,double  wage) {
        super(firstName, laststName, ssn);
        this.setHours(hours);
        this.setWage(wage);
       
    }

    public double getWage() {
        return wage;
    }

    public void setWage(double hourlyWage) {
            if(hourlyWage>=0.0){
       
            this.wage = hourlyWage;
        }else
            throw  new IllegalArgumentException("HourLY Wage must be >=0.0");
    }
   

    public double getHours() {
        return hours;
    }

    public void setHours(double hourWorked) {
        if(hourWorked>=0.0){
        this.hours = hourWorked;
        }else
            throw  new IllegalArgumentException("Hour must be >=0.0 and <=168"); //work hour per week 7*24hrs
    }
 

   
   
    @Override
    public double earnings() {
        if(getHours()<=40){
          return getWage()*getHours();
        }else{
        return getWage()*getHours()+(getHours()-40)*getWage()*1.5;
        }
       
   }
   @Override                                                            
      public String toString()                                             
      {                                                                    
      return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", super.toString(), "hourly wage" , getWage(), "hours worked", getHours() );
      }
}

SalariedEmployee.java
package employee;
/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
// SalariedEmployee concrete class extends abstract class Employee.
public class SalariedEmployee extends Employee{


   private double weeklySalary;
  
 
    public SalariedEmployee(String firstName, String laststName, String ssn,double salary) {
        super(firstName, laststName, ssn);
        
        this.setWeeklySalary(salary);
    }
    
    public double getWeeklySalary() {
        return weeklySalary;
    }

    public void setWeeklySalary(double salary) {
        if(salary>=0.0){
        this.weeklySalary = salary;
        }else 
            throw new IllegalArgumentException("Weekly Salary Must be >=0.0");
    }
    @Override
    public double earnings() {
        return  getWeeklySalary();
    }
   @Override
    public String toString(){
     return String.format("salaried employee: %s\n%s: $%,.2f", super.toString(), "weekly salary" , getWeeklySalary() );
}
}

CommissionEmployee.java

package employee;
/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qwkisoft.com
 */
public class CommissionEmployee extends Employee{
    private double grossSales;
    private double  commissionRate;



    public CommissionEmployee(String firstName, String laststName, String ssn,double  sales,double rate) {
        super(firstName, laststName, ssn);
        this.setCommissionRate(rate);
        this.setGrossSales(sales);
    }

    public double getGrossSales() {
        return grossSales;
    }

    public void setGrossSales(double sales) {
        if(sales>=0.0){
        this.grossSales = sales;
        }else
            throw new IllegalArgumentException("gross sales must be >0.0");
    }

    public double getCommissionRate() {
        return commissionRate;
    }

    public void setCommissionRate(double rate) {
        if(rate>0.0 && rate<1.0){
        this.commissionRate = rate;
        }else
            throw  new IllegalArgumentException("Commission rate must be >0 and <1.0");
    }



    @Override
    public double earnings() {
        return getGrossSales()*getCommissionRate();
   }
        @Override
    public String toString(){
    return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f","commission employee", super.toString(), "gross sales", getGrossSales(), "commission rate", getCommissionRate() );
    }
}
BasePlusCommissionEmployee .java

package employee;

/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qwkisoft.com
 */
public class BasePlusCommissionEmployee extends CommissionEmployee{

    private double baseSalary;
   
  

    public BasePlusCommissionEmployee(String firstName, String laststName, String ssn, double sales, double rate,double salary) {
        super(firstName, laststName, ssn, sales, rate);
        this.setBaseSalary(salary);
    }

    public double getBaseSalary() {
        return baseSalary;
    }

    public void setBaseSalary(double salary) {
        if(salary>=0.0){
        this.baseSalary = salary;
        }else
            throw  new IllegalArgumentException("Base salary must be >0.0");
    }

    // calculate earnings; override method earnings in CommissionEmployee
      @Override                                                           
      public double earnings()                                                   {                                                                   
      return getBaseSalary() + super.earnings();                       
     }                                          
  @Override                                                          
      public String toString()                                           
      {                                                                  
      return String.format( "%s %s; %s: $%,.2f",
             "base-salaried", super.toString(),                           
            "base salary", getBaseSalary() );                            
      }
   
}
TestClass .java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package employee;

/**
 *
 * @author Eng.Mghase
 * @email mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qwkisoft.com
 */
public class TestClass {

    public static SalariedEmployee salariedEmployee;
    public static HourlyEmployee hourlyEmployee;
    public static CommissionEmployee commissionEmployee;
    public static BasePlusCommissionEmployee basePlusCommissionEmployee;

    public static void main(String[] args) {
   
        // create four-element Employee array
        Employee[] employees = new Employee[4];

        // initialize array with Employees
        employees[0] =  new SalariedEmployee("Adam", "Gambo", "T111", 350000.00);
        employees[1] = new HourlyEmployee("Tumaini", "Shija", "T222", 16.00, 5000);
        employees[2] =  new CommissionEmployee("Scott", "Majanga", "T333", 3800000, 0.05);
        employees[3] = new BasePlusCommissionEmployee("Rose", "Mahuka", "T444", 2860000, .05, 450000);

        System.out.println("Employees processed polymorphically:\n");

        for (Employee currentEmployee : employees) {
            System.out.println(currentEmployee); // invokes toString

            if (currentEmployee instanceof BasePlusCommissionEmployee) {

                BasePlusCommissionEmployee employee = (BasePlusCommissionEmployee) currentEmployee;

                employee.setBaseSalary(1.10 * employee.getBaseSalary());

                System.out.printf( "new base salary with 10%% increase is: $%,.2f\n",  employee.getBaseSalary());
            }

            System.out.printf( "earned $%,.2f\n\n", currentEmployee.earnings());
        }

    }

}

Implementation the Shape hierarchy(Java )

Implement the Shape hierarchy shown in Figure below. Each Two-DimensionalShape should contain method getArea to calculate the area of the two-dimensional shape. Each ThreeDimensionalShape should have methods getArea and getVolume to calculate the surface area and volume, respectively, of the three-dimensional shape. Create a program that uses an array of Shape references to objects of each concrete class in the hierarchy. The program should print a text description of the object to which each array element refers. Also, in the loop that processes all the shapes in the array, determine whether each shape is a TwoDimensionalShape or a ThreeDimensionalShape. If it’s a TwoDimensionalShape, display its area. If it’s a ThreeDimensionalShape, display its area and volume.

ANSWER
Shape.java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public class Shape {
    
    @Override
    public String toString(){
        return String.format("%s\n",getClass().getName());
    }
    
}
TwoDimentionalShape.java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public abstract class TwoDimentionalShape extends Shape{
    public abstract double getArea();
   
    
}
ThreeDimensionalShape.java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public abstract class ThreeDimensionalShape extends Shape{
        public abstract double getVolume();
	public abstract double getArea();
    
}
Circle .java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public class Circle extends TwoDimentionalShape{
    private double radius;

    public Circle(double radius ) {
       this.radius=radius;
    }
    
    public void setRadius(double radius){
        this.radius=radius;
    }
    public double getRadius(){
        return radius;
    }
    

    @Override
    public double getArea() {
       return Math.PI*Math.pow(getRadius(), 2);
    }

    @Override
    public String toString() {
        return String.format("%sRadius: %.2f\n", super.toString(),getRadius());
    }
    
    
}
Square.java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public class Square extends TwoDimentionalShape{
    private double length;

    public Square(double length) {
        this.length=length;
    }

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }
       @Override
    public double getArea() {
        return Math.pow(getLength(), 2);
    }

    @Override
    public String toString() {
        return String.format("%sLength: %.2f\n",super.toString(),getLength());
    }

  
}

Triangle.java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 */
public class Triangle extends TwoDimentionalShape{
    private double  base,height;

    public Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    public void setBase(double base) {
        this.base = base;
    }

    public double getBase() {
        return base;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public double getHeight() {
        return height;
    }
    
    

    @Override
    public double getArea() {
        return  (getBase()*getHeight())/2;
    }

    @Override
    public String toString() {
        return String.format("%sBase: %.2f\nHeight: %.2f\n", super.toString(),getBase(),getHeight()); 
    }
    
    
}
Sphere.java
package plack6_qn01;


/**
 *
 * @author Eng.Mghase
 * @email  mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public class Sphere extends ThreeDimensionalShape{
    private double radius;
      
    public Sphere(double radius) {
        this.radius=radius;    
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }
 
     
    @Override
    public double getVolume() {
        return (4/3)*Math.PI*Math.pow(getRadius(), 3);
       
    }

    @Override
    public double getArea() {
       return (1/3)*Math.PI*Math.pow(getRadius(), 2);
    }

    @Override
    public String toString() {
        return String.format("%sRadius: %.2f", super.toString(),getRadius()); 
    }
    
}
Cube.java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 */
public class Cube extends ThreeDimensionalShape {

    private double edge;

    public Cube(double edge) {
        this.edge = edge;
    }

    public void setEdge(double edge) {
        this.edge = edge;
    }

    public double getEdge() {
        return edge;
    }

    @Override
    public double getArea() {
        return 6 * Math.pow(getEdge(), 2);
    }

    @Override
    public double getVolume() {
        return Math.pow(getEdge(), 3);
    }

    @Override
    public String toString() {
        return String.format("%sEdge: %.2f\n", super.toString(), getEdge());
    }
}
Tetrahedron.java
package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 * @email mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public class Tetrahedron extends ThreeDimensionalShape {

    private double edge;

    public Tetrahedron(double edge) {
        this.edge = edge;
    }

    public void setEdge(double edge) {
        this.edge = edge;
    }

    public double getEdge() {
        return edge;
    }

    @Override
    public double getArea() {
        return Math.sqrt(3) * Math.pow(getEdge(), 2);
    }

    @Override
    public double getVolume() {
        return Math.pow(getEdge(), 3) / (6 * Math.sqrt(2));
    }

    @Override
    public String toString() {
        return String.format("%sEdge: %.2f\n", super.toString(), getEdge());
    }
}


ShapeTest.java
package plack6_qn01;

package plack6_qn01;

/**
 *
 * @author Eng.Mghase
 * @email mghase.sadick1@gmail.com
 * @contact 0768454641
 * @web http://qksoftz.com
 */
public class ShapeTest {

    public static void main(String[] args) {
      
        Shape shape[] = new Shape[6];
        shape[0] = new Circle(7.0);
        shape[1] = new Square(7.0);
        shape[2] = new Triangle(4.0, 5.0);
        shape[3] = new Sphere(1.0);
        shape[4] = new Cube(1.0);
        shape[5] = new Tetrahedron(1.0);
        
        for (Shape curentShape : shape) {
            System.out.println(curentShape);
            if (curentShape instanceof TwoDimentionalShape) {
                TwoDimentionalShape twoDimentionalShape = (TwoDimentionalShape) curentShape;

                System.out.printf("%sArea: %.2f\n\n", twoDimentionalShape.toString(), twoDimentionalShape.getArea());

            } else if (curentShape instanceof ThreeDimensionalShape) {
                ThreeDimensionalShape threeDimensionalShape = (ThreeDimensionalShape) curentShape;
                System.out.printf("%sArea: %.2f\n\n", threeDimensionalShape.toString(), threeDimensionalShape.getVolume());

                System.out.printf("%sArea: %.2f\n\n", threeDimensionalShape.toString(), threeDimensionalShape.getArea());
            }

        }
    }
}