Monday, 23 March 2015

Calculating Rectangle Using User-defined Class in Java



The question is
  • Write a class named Rectangle to represent rectangle objects. The UML diagram for the class is shown below.  Then, write a program to test the class Rectangle. In this program, create three Rectangle objects. The first object has width 4 and height 40 while the second object has width 25 and height 20.5.  Assign any colors that you like. The third object has 1 for both width and height but the color is red. For this object, use the first constructor and then change the color to red using the appropriate method. Display the properties of these objects including their areas, perimeters and diagonal lengths.

dThe here is I declare Rectangle Class.



/*
 * 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 Exercise2;

/**
 *
 * @author Achmad Zulkarnain
 */
public class Rectangle {

    double width;
    double height;
    String color;

    public Rectangle() { //Default Constructor
        width = 1;
        height = 1;
        color = "green";
    }

    public Rectangle(double w, double h, String s) { //constructor
        width = w;
        height = h;
        color = s;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double w) {
        width = w;
    }

    public double getheight() {
        return height;
    }

    public void setHeight(double h) {
        height = h;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String c) {
        color = c;
    }

    public double getArea() {
        return width*height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public double getDiagonal() {
        return Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
    }
}


here I create another class which contain main method. Main method combine everything and which method should run.


package Exercise2;


public class javamain {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Rectangle obj1 = new Rectangle(4, 40, "Purple");
        Rectangle obj2 = new Rectangle(25, 20.5, "Blue");
        Rectangle obj3 = new Rectangle();
        
        
        //Object 1
        System.out.println("The first object has width: "+obj1.getWidth());
        System.out.println("The first object has height: "+obj1.getheight());
        System.out.println("The first object has color: "+obj1.getColor());
        System.out.println("The area of the first object is "+obj1.getArea());
        System.out.println("The parimeter of this  object is "+obj1.getPerimeter());
        System.out.println("The diagonal object is "+obj1.getDiagonal());
        
        System.out.println("#######################################");
        //Object 2
        System.out.println("The second object has width: "+obj2.getWidth());
        System.out.println("The second object has height: "+obj2.getheight());
        System.out.println("The second object has color: "+obj2.getColor());
        System.out.println("The area of the second object is "+obj2.getArea());
        System.out.println("The parimeter of this  object is "+obj2.getPerimeter());
        System.out.println("The diagonal object is "+obj2.getDiagonal());
        System.out.println("#######################################");
        
        System.out.println("The third object has width: "+obj3.getWidth());
        System.out.println("The third object has height: "+obj3.getheight());
        obj3.setColor("Red");
        System.out.println("The third object has color: "+obj3.getColor());
        System.out.println("The area of the third object is "+obj3.getArea());
        System.out.println("The parimeter of this  object is "+obj3.getPerimeter());
        System.out.println("The diagonal object is "+obj3.getDiagonal());
    }
    
}

Share:

Identify First Name and Surname (Bin and Binti) in Java

Maybe in Islam name, people has father's name after their name. For man, use "bin" and for woman use "binti". And how to identify name in Java using bin or binti??

boolean found = Arrays.asList(name.split(" ")).contains(keyword);

Code above is to identify whether in that name contain words in keyword. if the value is true then execute the program. If false, then execute something else.

here is the code in Java, I used array and use keyword to determine.

import java.util.Arrays;
import java.util.Scanner;

/**
 *
 * @author Achmad Zulkarnain
 */
public class Surname {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        String keyword = "binti";

        System.out.print("Please enter your full name> ");
        String name = in.nextLine();

        boolean found = Arrays.asList(name.split(" ")).contains(keyword);
        if (found) {
            int Index = name.indexOf("binti");
            System.out.println("Hello your name is " + name.substring(0, (Index)));
            System.out.println("And your father's name is " + name.substring(Index + 6));
        } else {
            int Index = name.indexOf("bin");
            System.out.println("Hello your name is " + name.substring(0, (Index)));
            System.out.println("And your father's name is " + name.substring(Index + 4));
        }
    }
}



Share:

Wednesday, 18 February 2015

Beautiful Creatures: Bees


One day in the afternoon, I'd watched TV program which showed one of the most beautiful creatures in the world, Bees. Why is it beautiful? There are so many benefit from it, starting from the larva until its honey itself. Additionally, its behavior on how to build their house (honeycomb), to serve their queen, and make mutual-ism symbioses between one another very unique to be discussed too.

Bees are flying insect closely related to ants and wasps, and are known for their role in pollination and for producing honey and beeswax (Wikipedia). Approximately 20k known species of bees in seven to nine recognized families. They live in every places where flowering-plants are available, except in Antarctica continent. They eat on nectar and pollen, primarily as an energy source that consist of protein and other nutrients. Mostly, pollen is used as food for baby bees (larvae). 


Here is the unique from bees! Bees consist of several caste that work according to the caste. They work exactly the same like ants and humans usually do, there is system inside the colony so they can complete the job awesomely without any jealousy one another. I can imagine how human work like that every day, our live will be very peaceful. 


Workers’s job is to find the nectar and pollen on flowering plants. This time, bees are doing multitask work. First, it does take the nectar and pollen for larvae in honeycomb and secondly it spreads the nectar in their feet to other flowers to make another “cross bred” (pollinating). That help flower to get natural insemination for making “fruits”. 'Workers' also make the honeycomb from fibrous part of wood + its enzyme, then going back to their nest to make it bigger by putting the fibrous + enzyme. It’s one of the action to serve their queen. LONG LIVE MY QUEEN! :)

I mentioned above that 'workers' only find and take the nectar + pollen. They can’t produce their own food. Then who are the chef of this emperor?? It’s LARVAE! Anyway, don’t judge the things by its size. Even though larvae is very small known as baby bees but larvae is the chef (they are good cooker). After larvae cook their food, they serve to the worker and queen. The good thing, it doesn’t waste their food like human. It saves some food in another bunker that 'workers' already made, it’s called HONEY. So, no more food wasted.

For your information

  • The temperature to make honeycomb is nearly fifty degrees Celsius (500 C), that’s why bees are using their wings to reduce temperature little bit down. 
  • Honey consist of ton of nutrients that human need in their live and to heal any illness. 
  •  Mostly bees are diurnal, active in the daylight. But there are four bees’ families (Andrenidae, Colletidae, Halictidae, and Apidae) that are nocturnal, active in the night. (Wikipedia).
  • Bees are humble and justice. They won’t attack you, if you don't disturb. If you attack them, they are willing to use their stings to entrust their live to defend their emperor. Once they sting, they will die.
  • Then why honeycomb has hexagonal shape? Because as I know, hexagonal is the best shape to preserve honey and not wasting place, meaning that its fit. 
  • Bees only attack your head ! WHY?? because bee detects carbon dioxide in our respiration system. So, when bees attack you, directly cover your head first and reduce your breathing.
Lastly, I’ve read quote from scholars but I forgot the name, maybe Imam Syafiie. 

“Live like a bee because they eat well, do well and produce good things”.

Eat well here is nectar and pollen from flowers, do well is pollinating to other flowers and lastly, produce good things are honey and bee pollen as medicine for human. Hey human, will you do the same??? Ask yourself!!

Share:

Sunday, 11 January 2015

Clinic Reservation in Java

This is one of the final project in our java programming class. Lecturer gave us task to complete the program with certain function to record patient details using simple array. Maybe this program is not 100% perfect, because maybe my logarithm skills is not good enough. I couldn't find the solution to delete element and if the element is empty shouldn't show. Anyway here is my code.

Here the output will be in console.

So, I will upload different method to explain every function of the method code.


This code above is the class on this program. All method and main method will be inside this bracket. What is class? I can assume that class is like motorbike, in motorbike has different name/brand. The object that has created from class will inherit the behavior from the class.


//Declare and assign the final value so that wont get change by another method
    public static final String[] name = new String[3];
    public static final int[] ic = new int[3];
    public static final String[] phone = new String[3];
    public static int i = 0;
    public static int sum = 0;

this code above is declaration of variable that has base value that can be accessed from all method inside the class. That's why, I declare outside from main method but inside the class. If state "final", it means that the value of the variable can be changed from any method function. So, the result will be final !


public static void main(String[] args) {

        int x, index,id;

       Scanner in = new Scanner(System.in);
        do {
        System.out.print("\n\nWelcome to the Automated Reservation Machine!\n");
        System.out.println("Select from the following menu options below:\n");
        System.out.println("========================");
        System.out.println("| [1]  Add Patient   |");
        System.out.println("| [2]  Print         |");
        System.out.println("| [3]  Search        |"); 
        System.out.println("| [4]  Edit          |");
        System.out.println("| [5]  Sum / Average |");
        System.out.println("========================");
        System.out.print("Please select your option now: ");
        x = in.nextInt();
            
            if (x==1){
               addPatient();           
            }
            
            else if (x==2){
                printPatient();  
            }
            
            else if (x==3){   
                System.out.print("Search patient by Id: ");
                id = in.nextInt();
                System.out.println("-----------------");
                index = getIndex(id);
                searchPatient(index);
            } 
            
            else if(x==4){
                System.out.println("Edit refers to Id!");
                System.out.print("Please enter Id: ");
                id = in.nextInt();
                System.out.println("-----------------");
                index = getIndex(id);
                searchPatient(index);
                if (index!=-1){
                    editData(index);
                }
            }
            
            else if(x==5){
                int r=0;
                if(name[r]==null){
                    System.out.println("Today we have no patient ");
                }
                else {   
                System.out.println("Average per day is RM "+averagePatient(sum));}
                System.out.println("Sum = RM "+sum);
            }
            
            else
                System.out.println("Please choose the option correctly");
        }while(x!=0);
}//end main method

The code above is the main method. Main method is the brain of the program. All method will work from calling the main method. It is called call method. If we have main method but we cannot utilize the main method, the other method will not work. So, main method has the important role.


public static void addPatient(){
        
       Scanner input = new Scanner(System.in);
       
            if(name[name.length-1]!=null){
                System.out.println("SORRY DATA IS FULL !!!"); //it will appear when data is full
            }
            else {
                System.out.print("\nPlease enter the name: ");
                name[i]  = input.nextLine();
                System.out.print("Please enter the phone number: ");
                phone[i] = input.nextLine();
                System.out.print("Please enter the Id: ");
                ic[i] = input.nextInt();
                sum+=5;
                i++;
            }
    }//end addPatient method

public static void editData(int z){
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter new name: ");
        name[z]=in.nextLine();
        System.out.print("Please enter new phone: ");
        phone[z]=in.nextLine();
        System.out.print("Please enter new Ic: ");
        ic[z]=in.nextInt();
        
    }//end editData method

The method above is to edit data inside the array. We can change the element of the array if we know the index of the array that we would like to change. How to get index of the array? we can use method getIndex().

The method above is how to print all the patient for each array. If the index of array name is null/empty, it will return "Sorry No Data Available", else it will print all the element.


public static int getIndex(int a){
        
        for (int d = 0; d < ic.length; d++)
      {
           if (ic[d] == a ) 
                 return d;  //We found it!!!
      }
        return -1;
    }//end getIndex method

As I told you above that we need getIndex method to know which index that we need to print, search and edit. We call that method then if the data is found, getIndex method will return the index to the calling method, and if not found it will return -1.

public static void searchPatient(int a){ 
        
        if(a==-1){ //Condition when return value from index not found -1
            System.out.println("\nThe  customer information is not found!!!");
            System.out.println("__________________________________");
        }
        else
        System.out.println(a+1+"\t\t"+name[a]+"\t\t"+phone[a]+"\t\t"+ic[a]);
    }//end searchPatient method

Search method is needed if we want to find data based on the id of the person. It also takes getIndex method to find the data. If not found it will return -1, and say "Customer information is not found", else it will print the exact information.

Lastly, I will upload all the codes in one class.

package patientreservation;

import java.util.Scanner;

public class PatientReservation {
    
    //Declare and assign the final value so that wont get change by another method
    public static final String[] name = new String[3];
    public static final String[] ic = new String[3];
    public static final String[] phone = new String[3];
    public static int i = 0;
    public static int sum = 0;

    public static void main(String[] args) {

        int x, index,id;

        Scanner in = new Scanner(System.in);
        do {
        System.out.print("\n\nWelcome to the Automated Reservation Machine!\n");
        System.out.println("Select from the following menu options below:\n");
        System.out.println("========================");
        System.out.println("| [1]  Add Patient   |");
        System.out.println("| [2]  Print Patient |");
        System.out.println("| [3]  Search Patient|"); 
        System.out.println("| [4]  Edit Patient  |");
        System.out.println("| [5]  Sum / Average |");
        System.out.println("| [6]  Delete        |");
        System.out.println("========================");
        System.out.print("Please select your option now: ");
        x = in.nextInt();
            
            if (x==1){
                addPatient();           
            }
            
            else if (x==2){
                printPatient();  
            }
            
            else if (x==3){   
                System.out.print("Search patient by Id: ");
                id = in.nextInt();
                System.out.println("-----------------");
                index = getIndex(id);
                searchPatient(index);
            } 
            
            else if(x==4){
                System.out.println("Edit refers to Id!");
                System.out.print("Please enter Id: ");
                id = in.nextInt();
                System.out.println("-----------------");
                index = getIndex(id);
                searchPatient(index);
                if (index!=-1){
                    editData(index);
                }
            }
            
            else if(x==5){
                int r=0;
                if(name[r]==null){
                    System.out.println("Today we have no patient :)");
                }
                else {   
                System.out.println("Average per day is RM "+averagePatient(sum));}
                System.out.println("Sum = RM "+sum);
            }
           
            else if(x==6){
                if(name[0]==null)
                {
                    System.out.println("Sorry no data available");
                }
                else {
                    System.out.print("Search patient by Id: ");
                    id = in.nextInt();
                    System.out.println("-----------------");
                    index = getIndex(id);
                    searchPatient(index);
                    
                        if(index!=-1){
                       deletePatient(index);   
                    }
                    
                }
            }
            else
                System.out.println("Please choose the option correctly");
        }while(x!=0);
}//end main method      
    
    public static void deletePatient(int a){
          name[a]="-";
          phone[a]="-";
          ic[a]="-";
          i--;
    }
    
    public static void addPatient(){
        
       Scanner input = new Scanner(System.in);
       
            if(name[name.length-1]=="-"){
                System.out.print("\nPlease enter the name: ");
                name[i]  = input.nextLine();
                System.out.print("Please enter the phone number: ");
                phone[i] = input.nextLine();
                System.out.print("Please enter the Id: ");
                ic[i] = input.nextLine();
            }
            else if(name[name.length-1]!=null){
                  System.out.println("SORRY DATA IS FULL !!!"); //it will appear when data is full
            }
            
            else {
                System.out.print("\nPlease enter the name: ");
                name[i]  = input.nextLine();
                System.out.print("Please enter the phone number: ");
                phone[i] = input.nextLine();
                System.out.print("Please enter the Id: ");
                ic[i] = input.nextLine();
                 
            }
            sum+=5;
            i++; 
    }//end addPatient method
    
    public static void printPatient(){
        
        System.out.println("______________________________________________________________");
        System.out.println("No.\t\tName\t\tPhone Number\t\tIC");
        System.out.println("--------------------------------------------------------------");
        
        int a=0;
        if(name[a]==null){
            System.out.println("SORRY NO DATA AVAILABLE !!!"); //when data is not available
        }
        else
           
            for(int j=0;j<ic.length;j++){
                
                if((name[j]==null)&&(phone[j]==null)&&(ic[j]==null))
                {
                    name[j]="-";
                    phone[j]="-";
                    ic[j]="-";
                }
                System.out.println(j+1+"\t\t"+name[j]+"\t\t"+phone[j]+"\t\t\t"+ic[j]);
            }
    }//end PrintPatient method
    
    public static double averagePatient(int d){
        
        return d/i;
        
    }//end averagePatient method

    public static void editData(int z){
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter new name: ");
        name[z]=in.nextLine();
        System.out.print("Please enter new phone: ");
        phone[z]=in.nextLine();
        System.out.print("Please enter new Ic: ");
        ic[z]=in.nextLine();
        
    }//end editData method
    
    public static int getIndex(int a){
        
        String s;
        s = Integer.toString(a);
        
        for (int i = 0; i < ic.length; i++)
      {
           if (ic[i].equals(s) ) 
                 return i;  //We found it!!!
      }
        return -1;
    }//end getIndex method
    
    public static void searchPatient(int a){ 
        
        if(a==-1){ //Condition when return value from index not found -1
            System.out.println("\nThe  customer information is not found!!!");
            System.out.println("__________________________________");
        }
        else
        System.out.println(a+1+"\t\t"+name[a]+"\t\t"+phone[a]+"\t\t"+ic[a]);
    }//end searchPatient method
}//endclass

Share: