Senin, 20 Maret 2017

Keliling dan Luas Bangun 2 Dimensi Program Java

Menghitung Keliling dan Luas Persegi, Persegi Panjang, Lingkaran, dan Segitiga

Berikut adalah program java untuk menghitung Keliling dan Luas pada persegi, persegi panjang, lingkaran, dan segitiga.

  • Persegi 
Source Code 
/**
 * Program Persegi
 * Menghitung Keliling dan Luas Persegi
 * Nama File : Persegi.java
 */
public class Persegi
{
    private int sisi;
    private int keliling;
    private int luas;
    
    public Persegi ( int s )
    {
        sisi = s;
    }
    
    public int getSisi ()
    {
        return sisi;
    }
    
    public int getKeliling ()
    {
        keliling = 4 * sisi;
        return keliling;
    }
    
    public int getLuas ()
    {
        luas = sisi * sisi;
        return luas;
    }
}


/**
 * Program PersegiTest
 * Menguji Program Persegi
 * Nama file : PersegiTest.java
 */

import java.util.Scanner;

public class PersegiTest
{
    public static void main ( String[] args )
    {
        Scanner scan = new Scanner ( System.in );
        int s;
        System.out.println ( "Masukkan sisi : " );
        s = scan.nextInt ();
        Persegi Psg = new Persegi (s);
        System.out.println ( "Keliling = " + Psg.getKeliling() );
        System.out.println ( "Luas = " + Psg.getLuas() );
    }
}

Output











  • Persegi Panjang
 Source Code

/**
 * Program Persegi Panjang
 * Menghitung Keliling dan Luas Persegi Panjang
 * Nama File : PersegiPanjang.java
 */
public class PersegiPanjang
{
    private int panjang;
    private int lebar;
    private int keliling;
    private int luas;
    
    public PersegiPanjang ( int p, int l )
    {
        panjang = p;
        lebar = l;
    }
    
    public int getPanjang ()
    {
        return panjang;
    }
    
    public int getLebar ()
    {
        return lebar;
    }
    
    public int getKeliling ()
    {
        keliling = 2 * ( panjang + lebar );
        return keliling;
    }
    
    public int getLuas ()
    {
        luas = panjang * lebar;
        return luas;
    }
}


/**
 * Program PersegiPanjangTest
 * Menguji Program Persegi Panjang
 * Nama file : PersegiPanjangTest.java
 */

import java.util.Scanner;

public class PersegiPanjangTest
{
    public static void main ( String[] args )
    {
        Scanner scan = new Scanner ( System.in );
        int p;
        int l;
        System.out.println ( "Masukkan panjang : " );
        p = scan.nextInt ();
        System.out.println ( "Masukkan lebar : " );
        l = scan.nextInt ();
        PersegiPanjang Psgpj = new PersegiPanjang ( p, l );
        System.out.println ( "Keliling = " + Psgpj.getKeliling() );
        System.out.println ( "Luas = " + Psgpj.getLuas() );
    }
}

Output













  • Lingkaran
Source Code


/**
 * Program Lingkaran
 * Menghitung Keliling dan Luas Lingkaran
 * Nama File : Lingkaran.java
 */
public class Lingkaran
{
    private double jarijari;
    private double keliling;
    private double luas;
    
    public Lingkaran ( double r )
    {
        jarijari = r;
    }
    
    public double getJarijari ()
    {
        return jarijari;
    }
    
    public double getKeliling ()
    {
        keliling = 2 * 3.14 * jarijari;
        return keliling;
    }
    
    public double getLuas ()
    {
        luas = 3.14 * jarijari * jarijari;
        return luas;
    }
}


/**
 * Program LingkaranTest
 * Menguji Program Lingkaran
 * Nama file : LingkaranTest.java
 */

import java.util.Scanner;

public class LingkaranTest
{
    public static void main ( String[] args )
    {
        Scanner scan = new Scanner ( System.in );
        double r;
        System.out.println ( "Masukkan jari-jari : " );
        r = scan.nextInt ();
        Lingkaran Lkr = new Lingkaran (r);
        System.out.println ( "Keliling = " + Lkr.getKeliling() );
        System.out.println ( "Luas = " + Lkr.getLuas() );
    }
}

Output











  • Segitiga
Source Code


/**
 * Program Segitiga
 * Menghitung Keliling dan Luas Segitiga Siku-siku
 * Nama File : Segitiga.java
 */
public class Segitiga
{
    private double alas;
    private double tinggi;
    private double sisimiring;
    private double keliling;
    private double luas;
    
    public Segitiga ( double a, double t, double sm )
    {
        alas = a;
        tinggi = t;
        sisimiring = sm;
    }
    
    public double getAlas ()
    {
        return alas;
    }
    
    public double getTinggi ()
    {
        return tinggi;
    }
   
    public double getSisimiring ()
    {
        return sisimiring;
    }
    
    public double getKeliling ()
    {
        keliling = alas + tinggi + sisimiring;
        return keliling;
    }
    
    public double getLuas ()
    {
        luas =  alas * tinggi / 2;
        return luas;
    }
}


/**
 * Program SegitigaTest
 * Menguji Program Segitiga Siku-siku
 * Nama file : SegitigaTest.java
 */

import java.util.Scanner;

public class SegitigaTest
{
    public static void main ( String[] args )
    {
        Scanner scan = new Scanner ( System.in );
        double a;
        double t;
        double sm;
        System.out.println ( "Masukkan alas : " );
        a = scan.nextInt ();
        System.out.println ( "Masukkan tinggi : " );
        t = scan.nextInt ();
        System.out.println ( "Masukkan sisi miring : " );
        sm = scan.nextInt ();
        Segitiga St = new Segitiga ( a, t, sm );
        System.out.println ( "Keliling = " + St.getKeliling() );
        System.out.println ( "Luas = " + St.getLuas() );
    }
}

Output

Senin, 06 Maret 2017

Latihan Java

A.  COMPOSITION
         Abstraction atau disebut juga composition merupakan prinsip penyederhanaan dari sesuatu yang           kompleks dengan cara memodelkan kelas sesuai dengan masalahnya.
         Misal sebuah motor jika dipecah-pecah bagian-bagiannya kita akan dapatkan seperti ban, mesin, kaca spion, rem, dll.  Hal ini juga berlaku sebaliknya. Jika kita gabungkan bagian-bagian tersebut maka kita akan mendapatkan sebuah kelas motor.

Contoh Program class Date, class Employee dan class EmployeeTest
Source code
// Date class declartion

public class Date
{
    private int month;  // 1-12
    private int day;    //1-31 based on monnth
    private int year;   // any year
    
    private static final int[] daysPerMonth = // days in each month
        { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        
    // constructor: call checkMonth to confirm proper value for month;
    // call checkDay to confirm proper value for day
    public Date( int theMonth, int theDay, int theYear )
    {
        month = checkMonth( theMonth ); // validate month
        year = theYear;                 // could validate year
        day = checkDay( theDay );       // validate day
        
        System.out.printf( "Date object constructor for date %s\n", this);
    } // end Date constructor
    
    // utility method to confirm proper month value
    private int checkMonth( int testMonth )
    {
        if ( testMonth > 0 && testMonth <= 12 ) // validate month
            return testMonth;
        else    // month is invalid
            throw new IllegalArgumentException( "month must be 1-12" );
    }   // end method checkMonth
    
    // utility method to confirm proper day value based on month and year
    private int checkDay( int testDay )
    {
        // check if day in range of month
        if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
            return testDay;
        // check for leap year
        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" );
    }   // end method checkDay
    
    // return a String of the form month/day/year
    public String toString()
    {
        return String.format( "%d/%d/%d", month, day, year );
    }   // end method toString
}   // end class Date

// Employee class with references to other objects.

public class Employee
{
    private String firstName;
    private String lastName;
    private Date birthDate;
    private Date hireDate;
    
    // constructor to initialize name, birth date and hire dat
    public Employee( String first, String last, Date dateOfBirth, Date dateofHire )
    {
        firstName = first;
        lastName = last;
        birthDate = dateOfBirth;
        hireDate = dateofHire;
    }   // end Employee constructor
    
    // convert Employee to String format
    public String toString()
    {
        return String.format( "%s, %s Hired: %s Birthday: %s", lastName, firstName, hireDate, birthDate );
    }   // end method toString
}   // end class Employee

// Composition demonstration

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 );
    }   // end main
}   // end class EmployeeTest

Output








B.  ENUMERATION
      Enumeration atau yang biasa disebut dengan Enum digunakan untuk mendefinisikan sekumpulan suatu konstanta yang me-representasi-kan pengenal yang unik. Layaknya sebuah class, enum dideklarasikan seperti halnya class, constructor, field, dan method. 

Contoh Program enum Book, class EnumTest
Source Code
// Declaring an enum type with constructor and explicit instance fields
// and accessors for these fields

public enum Book
{
    // declare constants of enum type
    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");
    
    // instance fields
    private final String title;         // book title
    private final String copyrightYear; // copyright year
    
    // enum constructor
    Book( String bookTitle, String year )
    {
        title = bookTitle;
        copyrightYear = year;
    }   // end enum Book constructor
    
    // accessor for field title
    public String getTitle()
    {
        return title;
    }   // end method getTitle
    
    // accessor for field copyrightYear
    public String getCopyrightYear()
    {
        return copyrightYear;
    }   // end method getCopyrightYear
}   // end enum Book

// Test enum type Book.
import java.util.EnumSet;

public class EnumTest
{
    public static void main( String[] args )
    {
        System.out.println( "All books:\n" );
        
        // print all books in enum Book
        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" );
        
        // print first four books
        for ( Book book : EnumSet.range( Book.JHTP, Book.CPPHTP ) )
           System.out.printf( "%-10s%-45s%s\n", book, book.getTitle(), book.getCopyrightYear() );
    }   // end main
}   // end class EnumTest

Output

















C.  STATIC VARIABLE
       Class variable atau static variable adalah variable yang di deklarasikan dengan menggunakan keyword "static". Class variable di deklarasikan di dalam kelas, tetapi diluar method atau blok statement. Static variable biasanya digunakan dalam mendefiniskan konstanta, yaitu variable yang mempunyai nilai tetap atau tidak dapat dirubah.

Contoh Program class Employee dan class EmployeeTest
Source Code
// Static variable used to maintain a count of the number of
// Employee objects in memory.

public class Employee
{
    private String firstName;
    private String lastName;
    private static int count = 0;   // number of Employees created
    
    // initialize Employee, add 1 to static count and
    // output String indicating that cunstructor was called
    public Employee( String first, String last )
    {
        firstName = first;
        lastName = last;
        
        ++count;    // increment static count of employees
        System.out.printf( "Employee constructor: %s %s; count = %d\n", firstName, lastName, count );
    }   // end Employee constructor
    
    // get first name
    public String getFirstName()
    {
        return firstName;
    }   // end method getFirstName
  
    // get last name
    public String getLastName()
    {
        return lastName;
    }   // end method getLastName
    
    // static  method to get static count value
    public static int getCount()
    {
        return count;
    }   // end method getCount
}   // end class Employee

// static member demonstration.

public class EmployeeTest
{
    public static void main( String[] args )
    {
        // show that count is 0 before creating Employees
        System.out.printf( "Employees before instantiation: %d\n", Employee.getCount() );
        
        // create two Employees; count should be 2
        Employee e1 = new Employee( "Susan", "Baker" );
        Employee e2 = new Employee( "Bob", "Blue" );
        
        // show that count is 2 after creating two Employees
        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", Employee.getCount() );
        
        // get names of Employees
        System.out.printf( "\nEmployee 1: %s %s\nEmployee 2: %s %s\n",
            e1.getFirstName(), e1.getLastName(), e2.getFirstName(), e2.getLastName() );
            
        // int this example, there is only one reference to each Employee,
        // so the following two statements indicate that these objects
        // are eligible for garbage collection
        e1 = null;
        e2 = null;
    }   // end main
}   // end class EmployeeTest

Output

Kamis, 02 Maret 2017

Source Code Java Ticket Machine

Program Ticket Machine
 
Source code class TicketMachine
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 BulueJ Line");
        System.out.println("# Ticket");
        System.out.println("# " + price + " cents.");
        System.out.println("##################");
        System.out.println();
        
        total = total + balance;
        
        balance = 0;
    }
}


Source code class TicketMachineTest
//Main
import java.util.Scanner;
public class TicketMachineTest
{
    public static void main(String args[])
    {
        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");
            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;
            }
        }
    }
}

Output