Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Sunday, 21 February 2016

Java: Inheritance Relationship with Example.

Association Vs Inheritance

Association: Association in Java establish relationship between two classes through their Objects. This relationship can be four type.

  • One to One
  • One to Many
  • Many to One
  • Many  to Many
Inheritance: Inheritance is a process where one class gain the properties (public field & method) of another class. The class which inherits the properties of other class is known as subclass(child/derived class) and the class whose properties will be inherited is known as super-class(parent/base class).

Difference: They both have code reuse ability but inheritance has the ownership of base class.

Keyword: extends

Case Study:

Suppose, In a Bank, there are two types of accounts.
  • Savings Account
  • Current Account
Both accounts have the following fields
  • Account Number
  • Account Name
  • Balance
and methods
  • Deposit
  • Withdraw
Savings account has interest rate and 
current account has service charge field.

Lets see the class diagram:
Class Diagram
Here, BankAccount is parent class and SavingsAccount & CurrentAccount are child class.

Savings account is not allowed to null the account balance and current account is allowed to take loan from bank.
So we have to overwrite the withdraw method for logic implementation.

Lets see the following code:

BankAccount Class:

// ADLabs


public class BankAccount {

 private String accountNO;
 private String accountName;
 private double balance;

 public BankAccount(String accountNO, String accountName) {
  this.accountNO = accountNO;
  this.accountName = accountName;

 }

 public BankAccount() {
  balance = 0;
 }

 public void deposit(double money) {
  balance += money;
  System.out.println("Money Successfully Deposited!");
 }

 public void withdraw(double money) {
  balance -= money;
  System.out.println("Balance :" + balance);
 }

 public double getBalance() {
  return balance;
 }

 public void setBalance(double balance) {
  this.balance = balance;
 }

}

SavingsAccount Class :
// ADLabs


public class SavingsAccount extends BankAccount {

 private float interestRate;

 public SavingsAccount(String accountNO, String accountName, float interestRate) {
  super(accountNO, accountName);
  this.interestRate = interestRate;
 }

 public void monthEndBalance() {
  float money = (float) (getBalance() + (getBalance() * (interestRate / 12)));
  System.out.println("Month End Balance will be :" + money);
 }

 public void withdraw(double money) {
  // Overwrite the super method.
  if (getBalance() - money >= 500) {
   super.withdraw(money);
  } else
   System.out.println("Insufficient Balance!");
 }
}


CurrentAccount Class:

// ADLabs


public class CurrentAccount extends BankAccount {
 private float serviceCharge;

 public CurrentAccount(String accountNO, String accountName, float serviceCharge) {
  super(accountNO, accountName);
  this.serviceCharge = serviceCharge;
 }

 public void monthEndBalance() {

  float money = (float) (getBalance() - (getBalance() * (serviceCharge / 12)));
  System.out.println("Month End Balance will be :" + money);
 }

 public void withdraw(double money) {
  // Overwrite the super method.
  double check = getBalance() - money;
  if (check < 0) {
   super.withdraw(money);
   System.out.println("You Loan from Bank :" + check);
  }
 }
}


main Class:
// ADLabs


public class StartPoint {

 public static void main(String[] args) {

  SavingsAccount account1 = new SavingsAccount("SA-1012", "Kopa Samsu", 5);
  CurrentAccount account2 = new CurrentAccount("CA-1023", "Musa Bin", 7);

  account1.deposit(5000);
  account2.deposit(5000);
  account1.monthEndBalance();
  account2.monthEndBalance();
  account1.withdraw(1000);
  account2.withdraw(5500);
 }

}


Console:

Money Successfully Deposited!
Money Successfully Deposited!
Month End Balance will be :7083.3335
Month End Balance will be :2083.3335
Balance :4000.0
Balance :-500.0
You Loan from Bank :-500.0


( ͡° ͜ʖ ͡°)
Happy Coding :)
-@D

Thursday, 18 February 2016

Java: Class Diagram & OneToOne Association Relationship.

Q: Create two classes and define one-to-one association relationship between them. Demonstrate it from "main" method.

//

Consider a person, in our case its Vai (Don) "Kopa Samsu".

( ͡° ͜ʖ ͡°)


// Profile
Name     : " Kopa Samsu "
Address : " D3, 22A Road, Dhaka, 1100 "

Mr. Kopa Samsu has only one Den that is the address specified in his profile.
Now, Create a Person Class and Address Class in our java project.


  • Person Class will contain firstName, lastName and personAddress attributes.
  • Address Class will contain houseNo, roadNo, postCode, district attributes.
  • Person Class will also use Calculator Class to find out the amount of Salami(money) to given to Vai.

  Class Diagram: One-to-One Association Relationship.


Address ClassPerson Class_1____________________>1



// Person Class CODE:


// ADLabs

public class Person {
 private String firstName;
 private String middleName;
 private String lastName;
 private Address personAddress;

 public void setPersonAddress(Address personAddress) {
  this.personAddress = personAddress;
 }

 public Address getPersonAddress() {
  return personAddress;
 }

 public String getFirstName() {
  return firstName;
 }

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

 public Person(String firstName, String middleName, String lastName) {
  this(firstName, lastName);
  setMiddleName(middleName);
 }

 public Person(String firstName, String lastName) {
  this();
  setFirstName(firstName);
  setLastName(lastName);
 }

 public Person() {

 }

 public double getSalami() {
  double basic = 10000;
  double specialCase = 5000;
  Calculator aCalc = new Calculator();
  double total = aCalc.add(basic, specialCase);
  return total;
 }

 public String getMiddleName() {
  return middleName;
 }

 public void setMiddleName(String middleName) {
  this.middleName = middleName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getFullName() {
  String fullName = firstName + " " + lastName;
  return fullName;
 }
}



// Address Class CODE
:

// ADLabs
public class Address {
 private String houseNo;
 private String roadNo;
 private String district;
 private int postCode;

 public Address(String houseNo, String roadNo, String district, int postCode) {
  this.houseNo = houseNo;
  this.roadNo = roadNo;
  this.postCode = postCode;
  this.district = district;
 }

 public String getHouseNo() {
  return houseNo;
 }

 public void setHouseNo(String houseNo) {
  this.houseNo = houseNo;
 }

 public String getRoadNo() {
  return roadNo;
 }

 public void setRoadNo(String roadNo) {
  this.roadNo = roadNo;
 }

 public int getPostCode() {
  return postCode;
 }

 public void setPostCode(int postCode) {
  this.postCode = postCode;
 }

 public String getDistrict() {
  return district;
 }

 public void setDistrict(String district) {
  this.district = district;
 }

}



// Calculator Class:

// ADLabs

public class Calculator {
 public double add(double n1, double n2) {
  return n1 + n2;
 }

 public double subtract(double n1, double n2) {
  return n1 - n2;
 }
}


// main Class Code:

// ADLabs

public class StartPoint {

 public static void main(String[] args) {

  Person aPerson = new Person();
  aPerson.setFirstName("Kopa");
  aPerson.setLastName("Samsu");

  Address address1 = new Address("D3", "22A", "Dhaka", 1100);

  aPerson.setPersonAddress(address1);

  System.out.println("Go to this Address :\n");
  System.out.println("Name: " + aPerson.getFullName());
  System.out.println("House Number: " + aPerson.getPersonAddress().getHouseNo());
  System.out.println("Road No: " + aPerson.getPersonAddress().getRoadNo());
  System.out.println("District :" + aPerson.getPersonAddress().getDistrict() + "\n");
  System.out.println("Give Salami :");
  System.out.println("Salami : " + aPerson.getSalami());
 }

}


Happy Coding :)
-@D

Tuesday, 16 February 2016

Java: Draw a Palindromic Pyramid / Triangle java program.

Problem: Palindromic Pyramid

Draw a palindromic pyramid or triangle of a given height.
Sample Input:
5
Sample Output:
        1
      121
    12321
  1234321
123454321

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Palindromic Triangle

  for (int i = 1; i <= n; i++) {

   for (int j = i; j < n; j++) {

    System.out.print(" ");
   }

   for (int k = 1; k <= i; k++)
    System.out.print(k);
   for (int l = i - 1; l > 0; l--)
    System.out.print(l);

   System.out.println();

  }

  sc.close();
 }

}




Console:

Enter any Int Num:5

        1
      121
    12321
  1234321
123454321

Happy Coding :)
-@D

Java: Draw a Palindrome java program.

Problem: Palindrome

Draw a palindrome of a given number.
Sample Input:
5
Sample Output:
1 2 3 4 5 4 3 2 1

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Palindrome

  for (int i = 1; i <= n; i++) {

   System.out.print(i + " ");
  }
  for (int i = n - 1; i > 0; i--)
   System.out.print(i + " ");

  System.out.println();

  sc.close();
 }

}




Console:

Enter any Int Num:5

1 2 3 4 5 4 3 2 1

Happy Coding :)
-@D

Java: Draw hollow pyramid java program.

Problem: Hollow Pyramid - Isosceles

Draw a hollow pyramid or triangle - isosceles of a given height.
Sample Input:
5
Sample Output:
        1
    1      3
  1          5
1              7
123456789

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Hollow Triangle – Isosceles

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

   for (int j = i; j < n - 1; j++) {

    System.out.print(" ");
   }

   for (int k = 1; k <= ((2 * i) + 1); k++) { // 2n+1= 1,3,5,7...

    if (i > 0 && i < n - 1) {
     if (k > 1 && k < 2 * i + 1) {
      System.out.print(" ");
     } else
      System.out.print(k);

    } else
     System.out.print(k);

   }
   System.out.println();

  }

  sc.close();
 }

}




Console:

Enter any Int Num:
        1
    1      3
  1          5
1              7
123456789

Happy Coding :)
-@D

Java: Draw Hollow Triangle - Right Justified - Reverse order java program.

Problem: Hollow Triangle - Right Justified

Draw a hollow right angled triangle of a given height.
Sample Input:
5
Sample Output:
        5
      45
    3  5
  2    5
12345

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Hollow Triangle - Right Justified - Reverse

  for (int i = n; i >= 1; i--) {

   for (int j = 1; j < i; j++) {
    System.out.print(" ");
   }
   for (int k = i; k <= n; k++) {
    if (i > 1 && i < n - 1) {
     if (k > i && k < n) {
      System.out.print(" ");
     } else
      System.out.print(k);
    } else
     System.out.print(k);
   }
   System.out.println();
  }

  sc.close();
 }

}



Console:

Enter any Int Num:5

        5
      45
    3  5
  2    5
12345

Happy Coding :)
-@D

Java: Draw Hollow Triangle - Left Justified java program.

Problem: Hollow Triangle.

Draw a hollow right angled triangle of a given height.

Sample Input:
5
Sample Output:
1
12
1  3
1    4
12345

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Hollow Triangle - Left Justified

  for (int i = 1; i <= n; i++) {

   for (int j = 1; j <= i; j++) {

    if (i > 2 && i < n) {
     if (j > 1 && j < i)
      System.out.print(" ");
     else
      System.out.print(j);
    } else
     System.out.print(j);
   }
   System.out.println();
  }

  sc.close();
 }

}




Console:

Enter any Int Num:5

1
12
1  3
1    4
12345

Happy Coding :)
-@D

Java: Draw a hollow Rectangle java program.

Problem: Hollow Rectangle

Draw a hollow rectangle of given height & width.
Sample Input:
height :  4
width  :  5

Sample Output:

12345
1      5
1      5
12345

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter height:");
  int row = sc.nextInt();
  System.out.print("Enter width:");
  int col = sc.nextInt();
  System.out.println();

  // Hollow Rectangle

  for (int i = 1; i <= row; i++) {

   for (int j = 1; j <= col; j++) {

    if (i == 1 || i == row) {
     System.out.print(j);
    } else if (j > 1 && j < col) {
     System.out.print(" ");
    } else
     System.out.print(j);

   }
   System.out.println();
  }

  sc.close();
 }

}




Console:

Enter height: 4
Enter width: 5

12345
1      5
1      5
12345

Happy Coding :)
-@D

Java: Draw Rhombus java program.

Problem: Rhombus

Draw a rhombus of given length.
Sample Input:
5
Sample Output:
        1
      123
    12345
  1234567
123456789
  1234567
    12345
     123
       1

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Rhombus

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

   for (int j = i; j < n - 1; j++) {

    System.out.print(" ");
   }
   for (int k = 1; k <= 2 * i + 1; k++) {

    System.out.print(k);
   }
   System.out.println();
  }
  for (int i = n - 2; i >= 0; i--) {

   for (int j = i; j <= n - 2; j++) {

    System.out.print(" ");
   }
   for (int k = 1; k <= 2 * i + 1; k++) {

    System.out.print(k);
   }
   System.out.println();
  }

  sc.close();
 }

}



Console:

Enter any Int Num:5

        1
      123
    12345
  1234567
123456789
  1234567
    12345
     123
       1

Happy Coding :)
-@D



Java: Draw a Pyramid / Triangle java program.

Problem: Pyramid Triangle-Isosceles.

Draw a pyramid or triangle of given height.
Sample Input:
5
Sample Output:
        1
      123
    12345
  1234567
123456789

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Triangle - Isosceles pyramid

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

   for (int j = i; j < n - 1; j++) {

    System.out.print(" ");
   }

   for (int k = 1; k <= ((2 * i) + 1); k++) { // 2n+1= 1,3,5,7...

    System.out.print(k);
   }
   System.out.println();

  }

  sc.close();
 }

}



Console:

Enter any Int Num:5

        1
      123
    12345
  1234567
123456789

Happy Coding :)
-@D

Java: Draw Triangle - Left Justified java program.

Program: Triangle - Left Justified

Draw right angled triangle of given height
Sample Input :
5
Sample Output:
1
12
123
1234
12345

Solve:
Lets see the following code:


// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();
  
  // Triangle - left justified
  
  for(int i=1; i<=n; i++ ){
   
   for(int j=1; j<=i; j++){
    
    System.out.print(j);
   }
   
   System.out.println();
  }
  
  
  sc.close();
 }

}

Console:

Enter any Int Num:5

1
12
123
1234
12345

Happy Coding :)
-@D

Java: Draw rectangle with two triangle java program.

Problem: Draw rectangle with two triangle java program

Sample Input:
5
Sample Output:
*####
**###
***##
****#
*****

Solve:
Lets see  the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();
  
  // Rectangle with two triangle
  for (int i = 1; i <= n; i++) {
   int j;
   for (j = 1; j <= i; j++) {
    System.out.print("*");
   }
   for (int j2 = j; j2 <= n; j2++) {
    System.out.print("#");
   }
   System.out.println();
  }
  
  
  sc.close();
 }

}

Console:

Enter any Int Num:5

*####
**###
***##
****#
*****


Happy Coding
-@D

Java: Draw Triangle - Left Justified - up side down java program.

Problem: Triangle - Left Justified

Draw right angled triangle of given height
Sample input:
5
Sample output
12345
1234
123
12
1

Solve:
Lets see the following code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();
  
  // Triangle - Left Justified - up side down
  for (int i = n; i >= 1; i--) {

   for (int j = 1; j <= i; j++) {
    System.out.print(j);
   }
   System.out.println();

  }
  
  sc.close();
 }

}

Console:
Enter any Int Num:5

12345
1234
123
12
1

Happy Coding :)
-@D

Saturday, 13 February 2016

Java: Kaprekar Number

Problem: Kaprekar Number

Consider an n-digit number k . Square it and add the right n digits to the left n or n-1 digits. If the resultant sum is k, then k is called a Kaprekar number.
For example, 9 is a Kaprekar number since
9^2 = 81, 8+1=9
and 297 is a Kaprekar number since
297^2=88 209, 88+209=297
The first few are 1, 9, 45, 55, 99, 297, 703, ...

Solve:
We consider a number in our case : 19044
Lets see the following Code:
// ADLabs


public class Kaprekar {

 public static void main(String[] args) {
      
  Kaprekar kaprekar = new Kaprekar();
  
  int inputNumber=19044; // input Number
  int inputNumberLength = kaprekar.length_of_num(inputNumber);
  int squareNumber = inputNumber*inputNumber;
  
  //int squareNumberLenght = kaprekar.length_of_num(squareNumber);
  int operator =(int) Math.pow(10, inputNumberLength);
  int rightDigits = squareNumber%(operator);
  int leftDigits = squareNumber/(operator);
  int sumDigits = rightDigits+leftDigits;
  if(inputNumber==sumDigits){
   System.out.println(inputNumber +" is Kaprekar Number");
  }else{
   System.out.println("Not a kaprekar"); 
  }
  
 }
  
 
 public int length_of_num(int num) {
  
  int length=0;
  while(num>0){
   
   num /= 10;
   length++;
  }
  return length;
 }

}




Console: Not a kaprekar

-@D

JAVA: Happy Number

Problem: Happy Number

Let the sum of the square of the digits of a positive integer S0 be represented by S1. In a similar way, let the sum of the squares of the digits of S1 be represented by S2 and so on. If Si = 1 for some i ³ 1, then the original integer S0 is said to be Happy number. A number, which is not happy, is called Unhappy number.
For example, 
7 is a Happy number since 7 -> 49 -> 97 -> 130 -> 10 -> 1 and 
4 is an Unhappy number since 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4.

Solve:

7 is Happy number-why? cause-

72 = 49
42 + 92 = 16 + 81 = 97
92 + 72 = 81 + 49 = 130
12 + 32 + 02 = 1+9+0 = 10
12 + 02 = 1

4 is Unhappy number because it never return to 0

Lets see the following code:
// ADLabs

import java.util.HashSet;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Set;


public class HappyNumber {

 // used to tell if a number has already been checked
 ArrayList checked = new ArrayList(); 
 
 public static void main(String[] args) {
  
  HappyNumber hn = new HappyNumber();
  Scanner sc =new Scanner(System.in);
  
  System.out.println("Happy Number Checker (to Stop enter 0)");
  System.out.print("Enter Number : ");
  
  int number = sc.nextInt();
  //System.out.print(hn.sum_sq_digits(number));
  //
  
  while (number>0) {
   
   if (hn.isHappy(number)) {
   System.out.println(number + " is Happy Number :)");
   }else {
   System.out.println(number + " is UnHappy Number :(");
   }
   System.out.print("Enter Number : ");
   number = sc.nextInt();
  }
  //
  sc.close();
 }

 
 public boolean isHappy(int i) {
    
  Set check = new HashSet();
  
  while (check.add(i)) //add and check database and return true
        {
            
            i = sum_sq_digits(i); //return sum of 2 
            System.out.print(i +" ");
            if (i==1)
             break; 
        }
  System.out.println("");
        
  
  return i==1; // if i=1 return true
  
 } 
 
 public int sum_sq_digits(int number){
  
  int sum = 0;
        while (number > 0)
        {
         sum += Math.pow(number % 10, 2);
            number /= 10;
        }
        return sum;
 }
 
}





Console:



Console Output
Console Output

Wednesday, 10 February 2016

JAVA: Create a bank account feature with ArrayList

Program 1: Create a bank account that deposit & withdraw money from a account and show account details using Array-List.

Solution: We need two classes
1. Account - that handles deposit & withdraw methods.
2. main - that handles Array-List & Account class.

Account Class Code:


Account Class Code





















Account Class Code































main Class Code:






























































































Output Console :

Menu
















Account Create

















Account Details























Deposit Money
























Withdraw Money






















Service Close

















Done! @D