Selasa, 07 Maret 2017

composition, enumerations and static class


1. Composition
Composition adalah dimana hubungan suatu object bergantung dengan objek lainnya.

program 8.7

/**
 * Write a description of class Date here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Date
    {
      private int month;
      private int day;
      private int year;
      private static final int[] daysPerMonth = 
      { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
      public Date( int theMonth, int theDay, int theYear )
        {
          month = checkMonth( theMonth );
          year = theYear;
          day = checkDay( theDay );
          System.out.printf("Date object constructor for date %s\n", this );
        }
    private int checkMonth( int testMonth )
        {
          if ( testMonth > 0 && testMonth <= 12 )
          return testMonth;
        
          else
          throw new IllegalArgumentException( "month must be 1-12" );
        }
    private int checkDay( int testDay )
       {
        if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
        return testDay;
        if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
        ( year % 4 == 0 && year % 100 != 0 ) ) )
        return testDay;
        throw new IllegalArgumentException
        ("day out-of-range for the specified month and year" );
       }
    public String toString()
    {
        return String.format( "%d/%d/%d", month, day, year );
    }
}


program 8.8

/**
 * Write a description of class Employee here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Employee
{
    private String firstName;
    private String lastName;
    private Date birthDate;
    private Date hireDate;
   public Employee( String first, String last, Date dateOfBirth,
   Date dateOfHire )
   {
      firstName = first;
      lastName = last;
      birthDate = dateOfBirth;
      hireDate = dateOfHire;
   }
   public String toString()
    {
        return String.format( "%s, %s Hired: %s Birthday: %s",
        lastName, firstName, hireDate, birthDate );
    }
}



program 8.9

/**
 * Write a description of class EmployeeTest here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class EmployeeTest
{
    public static void main( String[] args )
    {
        Date birth = new Date( 7, 24, 1949 );
        Date hire = new Date( 3, 12, 1988 );
        Employee employee = new Employee( "Bob", "Blue", birth, hire );
        System.out.println( employee );
    }
 }



2. Enumerations
Enumeration adalah kumpulan nama-nama konstant yang didefinisikan sebagai tipe data baru. Sebuah objek bertipe Enumeration dapat mengakses isi dari kumpulan nilai pada enumeration.
program 8.10

/**
 * Write a description of class Book here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public enum Book
{
    JHTP( "Java How to Program", "2012" ),
    CHTP( "C How to Program", "2007" ),
    IW3HTP( "Internet & World Wide Web How to Program", "2008" ),
    CPPHTP( "C++ How to Program", "2012" ),
    VBHTP( "Visual Basic 2010 How to Program", "2011" ),
    CSHARPHTP( "Visual C# 2010 How to Program", "2011" );
    private final String title;
    private final String copyrightYear;
    Book( String bookTitle, String year )
    {
        title = bookTitle;
        copyrightYear = year;
    }
    public String getTitle()
    {
        return title;
    }
    public String getCopyrightYear()
    {
        return copyrightYear;
    } // end method getCopyrightYear
}


program 8.11

/**
 * Write a description of class EnumTest here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
import java.util.EnumSet;
    public class EnumTest
    {
        public static void main( String[] args )
        {
           System.out.println( "All books:\n" );
           for( Book book : Book.values() )
            System.out.printf("%-10s%-45s%s\n", book,
            book.getTitle(), book.getCopyrightYear());
       System.out.println("\nDisplay a range of enum constants:\n" );
       for( Book book : EnumSet.range (Book.JHTP, Book.CPPHTP ))
            System.out.printf("%-10s%-45s%s\n", book,
            book.getTitle(), book.getCopyrightYear());
        }
    }


3. Static Class Members
Apabila sebuah variabel didefinisikan static didalam sebuah class, maka untuk memanggil variabel tersebut kita tidak perlu membuat objek dari class tersebut, namun langsung bisa memanggil variabel tersebut dari nama class dimana dia dideklarasikan.


program 8.12

/**
 * Write a description of class Employee2 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */

public class Employee2
{
    private String firstName;
    private String lastName;
    private static int count = 0;
    public Employee2( String first, String last )
        {
            firstName = first;
            lastName = last;
            ++count;

            System.out.printf( "Employee constructor: %s %s; count = %d\n",
            firstName, lastName, count );
        }
    public String getFirstName()
    {
    return firstName;
    }
    public String getLastName()
    {
        return lastName;
    }

    public static int getCount()
    {
        return count;
    }
}



program 8.13

/**
 * Write a description of class Employee2Test here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Employee2Test
{
    public static void main (String[] args)
    {
        System.out.printf("Employees before instantiation: %d\n",Employee2.getCount ());
    
        Employee2 e1= new Employee ("Susan", "Baker");
        Employee2 e2= new Employee ("Bob", "Blue");
    
        System.out.println( "\nEmployees after instantiation: " );
        System.out.printf( "via e1.getCount(): %d\n",e1.getCount() );
        System.out.printf( "via e2.getCount(): %d\n",e2.getCount() );
        System.out.printf( "via Employee.getCount(): %d\n",Employee2.getCount());

        System.out.printf( "\nEmployee 1: %s %s\nEmployee 2: %s %s\n",
        e1.getFirstName(), e1.getLastName(),
        e2.getFirstName(), e2.getLastName() );
        e1= null;
        e2 = null;
    }
}







Minggu, 05 Maret 2017

Ticket Machine



Ticket Machine adalah sebuah mesin seperti ATM, yang berfungsi melayani penjualan tiket kereta api dari satu tujuan ke tujuan yang lain. Di dalam Ticket Machine ada sebuah program atau perangkat lunak yang mengatur harga tiket di tiap tujuan, mengatur kembalian uang, dan juga mencetak receipt sebagai bukti pembelian tiket.

Berikut implementasikan programnya menggunakan Blue J.



/**
 * Write a description of class TicketMachine here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class TicketMachine  
 {  
   private int price;  
   private int balance;  
   private int total;  
   public TicketMachine(int ticketCost)  
   {  
     price = ticketCost;  
     balance = 0;  
     total = 0;  
   }  
   public int getPrice()  
   {  
     return price;  
   }  
   public int getBalance()  
   {  
     return balance;  
   }  
   public void insertMoney(int amount)  
   {  
     balance = balance + amount;  
   }  
   public void printTicket()  
   {  
     System.out.println("@@@@@@@@@@@@@@@@@@");  
     System.out.println("@ The BlueJ Line @");  
     System.out.println("@ Ticket     @");  
     System.out.println("" + price + " cents.");  
     System.out.println();  
     total = total + balance;  
     balance = 0;  
   }  
 }



/**
 * Write a description of class IntMain here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
 import java.util.Scanner;  
 public class IntMain  
 {  
    public static int main()  
       {  
         Scanner scan = new Scanner(System.in);  
         int cost,menu;  
         System.out.println("Masukkan harga tiket \n");  
         cost=scan.nextInt();  
         TicketMachine ticket=new TicketMachine(cost);  
         while (true){  
           System.out.println("1. Get Price");  
           System.out.println("2. Get Balance");  
           System.out.println("3. Insert Money");  
           System.out.println("4. Print Ticket");  
           System.out.println("5. EKZIT");  
           menu=scan.nextInt();  
         switch(menu)  
         {  
           case 1:  
           cost=ticket.getPrice();  
           System.out.println(cost);  
           break;  
           case 2:  
           System.out.println(ticket.getBalance());  
           break;  
           case 3:  
           int money=scan.nextInt();  
           ticket.insertMoney(money);  
           break;  
           case 4:  
           ticket.printTicket();  
           break;  
           case 5:  
           return 0;  
         }  
       }  
     }  
   }