Tuesday, November 22, 2016

Desimal jadi Hexadesimal

Kodenya

import java.util.Scanner;
class DecimalToHexExample
{
    public static void main(String args[])
    {
      Scanner input = new Scanner( System.in );
      System.out.print("Enter a decimal number : ");
      int num =input.nextInt();
       
      // calling method toHexString()
      String str = Integer.toHexString(num);
      System.out.println("Method 1: Decimal to hexadecimal: "+str);
    }
}

Hasilnya:


Contoh Program If Else

Kodenya:

import java.util.Scanner;
public class Everything {
    public static void main(String[] args) {
        Scanner masukan = new Scanner (System.in);
     
        double x=0,z=0,   e=0,n=0;
        int nilai=0;
     
     
     
        System.out.println("all in One");
        System.out.println("mau apa??");
        System.out.println("1. pembagian ");
        System.out.println("2. perkalian");
        System.out.println("3. beli rumah angker");
        System.out.println("4. makan makanan mahal");
       nilai = masukan.nextInt();
     
       if (nilai==1){
        System.out.println("masukkan nilai 1");
        x = masukan.nextInt();
        System.out.println("masukan nilai 2");
        z = masukan.nextInt();
           System.out.println("");
           System.out.println("hasilnya adalah");
           System.out.println(x/z);
       }
     
      //kalian
       else if  (nilai==2){
            System.out.println("masukkan nilai 1");
        x = masukan.nextInt();
        System.out.println("masukan nilai 2");
        z = masukan.nextInt();
           System.out.println("");
           System.out.println("hasilnya adalah");
           System.out.println(x*z);  
       }
     
       //rumah
       else if (nilai==3) {
           System.out.println("harga rumah" );
           z=z+100;
           System.out.println(z);
           System.out.println(" mau di renovasi() atau diperbaiki(2)");
       nilai= masukan.nextInt();
        if (nilai==1) {
           System.out.println("ya? tammbah 300");
           e=z+300;
           System.out.println("jimlah total"+ e);
       }
       else if (nilai==2) {
           System.out.println("ya? tambah 500");
           e=z+500;
           System.out.println(e);
       }
       }

     
   
       //makanan
        if (nilai==4) {
            System.out.println("Zen Resto");
        System.out.println("pilih apa yang kamu mau");
        System.out.println("1. nasgor");
        System.out.println("2. bebek");
        nilai=masukan.nextInt();
         
        switch (nilai) {
            case 1 :
                n = n+1000;
                System.out.println(n);
            case 2 :
                n= n+2000;
                System.out.println(n);
         
                System.out.println("mmakan lesehan (1), Apa di Bungkus (2)");
                nilai =masukan.nextInt();
                if (nilai==1) {
                    e = n +1000;
                    System.out.println("nambah 1000, jadi total = " + e);
                } else if (nilai==2) {
                e= n + 3000;
                System.out.println("nambah 3000, jadi total = " + e);
                }
             
        }

    }
}
}

Hasilnya:


Bubble Sort

Kodenya:

import java.util.Scanner;

class BubbleSort {
  public static void main(String []args) {
    int n, c, d, swap;
    Scanner in = new Scanner(System.in);

    System.out.println("Input number of integers to sort");
    n = in.nextInt();

    int array[] = new int[n];

    System.out.println("Enter " + n + " integers");

    for (c = 0; c < n; c++)
      array[c] = in.nextInt();

    for (c = 0; c < ( n - 1 ); c++) {
      for (d = 0; d < n - c - 1; d++) {
        if (array[d] > array[d+1]) /* For descending order use < */
        {
          swap       = array[d];
          array[d]   = array[d+1];
          array[d+1] = swap;
        }
      }
    }

    System.out.println("Sorted list of numbers");

    for (c = 0; c < n; c++)
      System.out.println(array[c]);
  }
}

Hasilnya


Binary jadi Desimal

Kodenya

import java.util.Scanner;
class BinaryToDecimal {
    public static void main(String args[]){
       Scanner input = new Scanner( System.in );
       System.out.print("Enter a binary number: ");
       String binaryString =input.nextLine();
       System.out.println("Output: "+Integer.parseInt(binaryString,2));
    }
}

Hasilnya


Reverse Menggunakan For

Kodenya

import java.util.Scanner;
class ForLoopReverseDemo
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      /* for loop: No initialization part as num is already
       * initialized and no increment/decrement part as logic
       * num = num/10 already decrements the value of num
       */
      for( ;num != 0; )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of specified number is: "+reversenum);
   }
}

Hasilnya


Reverse dengan menggunakan Rekursi

Kodenya:

import java.util.Scanner;
class RecursionReverseDemo
{
   //A method for reverse
   public static void reverseMethod(int number) {
       if (number < 10) {
  System.out.println(number);
  return;
       }
       else {
           System.out.print(number % 10);
           //Method is calling itself: recursion
           reverseMethod(number/10);
       }
   }
   public static void main(String args[])
   {
int num=0;
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
System.out.print("Reverse of the input number is:");
reverseMethod(num);
System.out.println();
   }
}

Hasilnya:


Reverse menggunakan While

Kodenya

import java.util.Scanner;
class ReverseNumberWhile
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      //While Loop: Logic to find out the reverse number
      while( num != 0 )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of input number is: "+reversenum);
   }
}

Hasilnya:


Menjumlahkan Array

Kodenya

class SumOfArray{
   public static void main(String args[]){
      int[] array = {10, 20, 30, 40, 50, 10};
      int sum = 0;
      //Advanced for loop
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}

hasilnya


Menduplikat

Kodenya


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class duplicate
 {

  public void countDupChars(String str){

    //Create a HashMap
    Map<Character, Integer> map = new HashMap<Character, Integer>();

    //Convert the String to char array
    char[] chars = str.toCharArray();

    /* logic: char are inserted as keys and their count
     * as values. If map contains the char already then
     * increase the value by 1
     */
    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
    }

    //Obtaining set of keys
    Set<Character> keys = map.keySet();

    /* Display count of chars if it is
     * greater than 1. All duplicate chars would be
     * having value greater than 1.
     */
    for(Character ch:keys){
      if(map.get(ch) > 1){
        System.out.println("Char "+ch+" "+map.get(ch));
      }
    }
  }

  public static void main(String a[]){
    duplicate obj = new duplicate();
    System.out.println("String: BeginnersBook.com");
    System.out.println("-------------------------");
    obj.countDupChars("BeginnersBook.com");

    System.out.println("\nString: ChaitanyaSingh");
    System.out.println("-------------------------");
    obj.countDupChars("ChaitanyaSingh");

    System.out.println("\nString: #@$@!#$%!!%@");
    System.out.println("-------------------------");
    obj.countDupChars("#@$@!#$%!!%@");
  }
}

Hasilnya



Contoh Vector

Kodenya

import java.util.*;

public class VectorExample {

   public static void main(String args[]) {
      /* Vector of initial capacity(size) of 2 */
      Vector<String> vec = new Vector<String>(2);

      /* Adding elements to a vector*/
      vec.addElement("Apple");
      vec.addElement("Orange");
      vec.addElement("Mango");
      vec.addElement("Fig");

      /* check size and capacityIncrement*/
      System.out.println("Size is: "+vec.size());
      System.out.println("Default capacity increment is: "+vec.capacity());

      vec.addElement("fruit1");
      vec.addElement("fruit2");
      vec.addElement("fruit3");

      /*size and capacityIncrement after two insertions*/
      System.out.println("Size after addition: "+vec.size());
      System.out.println("Capacity after increment is: "+vec.capacity());

      /*Display Vector elements*/
      Enumeration en = vec.elements();
      System.out.println("\nElements are:");
      while(en.hasMoreElements())
         System.out.print(en.nextElement() + " ");
   }
}

hasilnya


Menampilkan 100 angka prima

Kodenya:

class PrimeNumber100Demo
{
   public static void main(String args[])
   {
      int n;
      int status = 1;
      int num = 3;
      System.out.println("First 100 prime numbers are:");   
      System.out.println(2);
      for ( int i = 2 ; i <=100 ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            i++;
         }
         status = 1;
         num++;
      }         
   }
}

Hasilnya:



Contoh hash

Kodenya

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Hash {
   public static void main(String args[]) {

      /* This is how to declare HashMap */
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();

      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");
      hmap.put(7, "Singh");
      hmap.put(49, "Ajeet");
      hmap.put(3, "Anuj");

      /* Display content using Iterator*/
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }

      /* Get values based on key*/
      String var= hmap.get(2);
      System.out.println("Value at index 2 is: "+var);

      /* Remove values based on key*/
      hmap.remove(3);
      System.out.println("Map key and values after removal:");
      Set set2 = hmap.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
          Map.Entry mentry2 = (Map.Entry)iterator2.next();
          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
          System.out.println(mentry2.getValue());
       }

   }
}


Hasilnya:


Contoh Tree

Kodenya:

import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;

public class Tree {

   public static void main(String args[]) {

      /* This is how to declare TreeMap */
      TreeMap<Integer, String> tmap =
             new TreeMap<Integer, String>();

      /*Adding elements to TreeMap*/
      tmap.put(1, "Data1");
      tmap.put(23, "Data2");
      tmap.put(70, "Data3");
      tmap.put(4, "Data4");
      tmap.put(2, "Data5");

      /* Display content using Iterator*/
      Set set = tmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }

   }
}

hasilnya:


Medapatkan Nilai Maksimum dari dua angka

Kodenya:

public class FindMaxOfTwoNumbersExample {

  public static void main(String[] args) {
 
    /*
     * To find maximum of two int values, use
     * static int max(int a, int b) method of Math class.
     */
 
    System.out.println(Math.max(20,40));
 
    /*
     * To find minimum of two float values, use
     * static float max(float f1, float f2) method of Math class.
     */
     System.out.println(Math.max(324.34f,432.324f));

    /*
     * To find maximum of two double values, use
     * static double max(double d2, double d2) method of Math class.
     */
     System.out.println(Math.max(65.34,123.45));
 
    /*
     * To find maximum of two long values, use
     * static long max(long l1, long l2) method of Math class.
     */
             
     System.out.println(Math.max(435l,523l));
  }

Hasilnya:

Find Floor Number

Kodenya


public class FindFloorValueExample {

  public static void main(String[] args) {
 
    /*
     * To find a floor value, use
     * static double floor(double d) method of Math class.
     *
     * It returns a largest integer which is not grater than the argument value.
     */
 
    //Returns the same value
    System.out.println(Math.floor(70));
 
    //returns largest integer which is not less than 30.1, i.e. 30
    System.out.println(Math.floor(30.1));
 
    //returns largest integer which is not less than 15.5, i.e. 15
    System.out.println(Math.floor(15.5));
 
    //in this case it would be -40
    System.out.println(Math.floor(-40));
 
    //it returns -43.
    System.out.println(Math.floor(-42.4));
 
    //returns 0
    System.out.println(Math.floor(0));
 
  }
}

Hasilnya


Contoh Do While Loop

Kodenya

class DoWhileLoopExample {
    public static void main(String args[]){
         int i=10;
         do{
              System.out.println(i);
              i--;
         }while(i>1);
    }
}

Hasilnya:

Mendapatkan Input Data

Kodenya:

import java.util.Scanner;

class GetInputData
{
  public static void main(String args[])
  {
     int num;
     float fnum;
     String str;

     Scanner in = new Scanner(System.in);

     //Get input String
     System.out.println("Enter a string: ");
     str = in.nextLine();
     System.out.println("Input String is: "+str);

     //Get input Integer
     System.out.println("Enter an integer: ");
     num = in.nextInt();
     System.out.println("Input Integer is: "+num);

     //Get input float number
     System.out.println("Enter a float number: ");
     fnum = in.nextFloat();
     System.out.println("Input Float number is: "+fnum);
  }
}

Hasilnya:


Mencari Angka Exponesial

Kodenya

public class FindExponentialNumberExample {

  public static void main(String[] args)
  {
       /*
     * To find exponential value of a number, use
     * static double exp(double d) method of Java Math class.
     *
     * It returns e raised to argument value.
     */
 
     System.out.println("Exponential of 2 is : " + Math.exp(2));
  }
}

Hasilnya


Decimal Binary Stack

Kodenya

import java.util.*;
class DecimalBinaryStack
{
  public static void main(String[] args)
  {
    Scanner in = new Scanner(System.in);

    // Create Stack object
    Stack<Integer> stack = new Stack<Integer>();

    // User input
    System.out.println("Enter decimal number: ");
    int num = in.nextInt();

    while (num != 0)
    {
      int d = num % 2;
      stack.push(d);
      num /= 2;
    }

    System.out.print("\nBinary representation is:");
    while (!(stack.isEmpty() ))
    {
      System.out.print(stack.pop());
    }
    System.out.println();
  }
}

Hasilnya


Membuat Angka Asal

Kodenya

import java.util.*;
class GenerateRandomNumber {
   public static void main(String[] args) {
      int counter;
      Random rnum = new Random();
      /* Below code would generate 5 random numbers
       * between 0 and 200.
       */
      System.out.println("Random Numbers:");
      System.out.println("***************");
      for (counter = 1; counter <= 5; counter++) {
         System.out.println(rnum.nextInt(200));
      }
   }
}

Haislnya:



Ganjil atau Genap

Kodenya

import java.util.Scanner;

class CheckEvenOdd
{
  public static void main(String args[])
  {
    int num;
    System.out.println("Enter an Integer number:");

    //The input provided by user is stored in num
    Scanner input = new Scanner(System.in);
    num = input.nextInt();

    /* If number is divisible by 2 then it's an even number
     * else odd number*/
    if ( num % 2 == 0 )
        System.out.println("Entered number is even");
     else
        System.out.println("Entered number is odd");
  }
}


Hasilnya


Membandingkan String

Kodenya

import java.util.Scanner;

class CompareStrings
{
   public static void main(String args[])
   {
      String s1, s2;
      Scanner in = new Scanner(System.in);

      System.out.println("Enter the first string");
      s1 = in.nextLine();

      System.out.println("Enter the second string");
      s2 = in.nextLine();

      if ( s1.compareTo(s2) > 0 )
         System.out.println("First string is greater than second.");
      else if ( s1.compareTo(s2) < 0 )
         System.out.println("First string is smaller than second.");
      else  
         System.out.println("Both strings are equal.");
   }
}

Hasilnya


Swap Number

Kodenya

import java.util.Scanner;

class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y, temp;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);

      x = in.nextInt();
      y = in.nextInt();

      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);

      temp = x;
      x = y;
      y = temp;

      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}

Hasilnya:


Segitiga Floyd

Codenya:

import java.util.Scanner;

class FloydTriangle
{
   public static void main(String args[])
   {
      int n, num = 1, c, d;
      Scanner in = new Scanner(System.in);

      System.out.println("Enter the number of rows of floyd's triangle you want");
      n = in.nextInt();

      System.out.println("Floyd's triangle :-");

      for ( c = 1 ; c <= n ; c++ )
      {
         for ( d = 1 ; d <= c ; d++ )
         {
            System.out.print(num+" ");
            num++;
         }

         System.out.println();
      }
   }
}

Hasilnya:


Armstrong Number

Codenya:

import java.util.Scanner;

class ArmstrongNumber
{
   public static void main(String args[])
   {
      int n, sum = 0, temp, remainder, digits = 0;

      Scanner in = new Scanner(System.in);
      System.out.println("Input a number to check if it is an Armstrong number");    
      n = in.nextInt();

      temp = n;

      // Count number of digits

      while (temp != 0) {
         digits++;
         temp = temp/10;
      }

      temp = n;

      while (temp != 0) {
         remainder = temp%10;
         sum = sum + power(remainder, digits);
         temp = temp/10;
      }

      if (n == sum)
         System.out.println(n + " is an Armstrong number.");
      else
         System.out.println(n + " is not an Armstrong number.");        
   }

   static int power(int n, int r) {
      int c, p = 1;

      for (c = 1; c <= r; c++)
         p = p*n;

      return p;  
   }
}


Hasilnya:


Membuka Notepad

Codenya:

import java.util.*;
import java.io.*;

class Notepad {
  public static void main(String[] args) {
    Runtime rs = Runtime.getRuntime();

    try {
      rs.exec("notepad");
    }
    catch (IOException e) {
      System.out.println(e);
    }  
  }
}

Hasilnya:


Transpose Matriks

Codenya:

import java.util.Scanner;

class TransposeAMatrix
{
   public static void main(String args[])
   {
      int m, n, c, d;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of rows and columns of matrix");
      m = in.nextInt();
      n = in.nextInt();

      int matrix[][] = new int[m][n];

      System.out.println("Enter the elements of matrix");

      for ( c = 0 ; c < m ; c++ )
         for ( d = 0 ; d < n ; d++ )
            matrix[c][d] = in.nextInt();

      int transpose[][] = new int[n][m];

      for ( c = 0 ; c < m ; c++ )
      {
         for ( d = 0 ; d < n ; d++ )              
            transpose[d][c] = matrix[c][d];
      }

      System.out.println("Transpose of entered matrix:-");

      for ( c = 0 ; c < n ; c++ )
      {
         for ( d = 0 ; d < m ; d++ )
               System.out.print(transpose[c][d]+"\t");

         System.out.print("\n");
      }
   }
}

Hasilnya:


Perkalian Matrix

Codenya:

import java.util.Scanner;

class MatrixMultiplication
{
   public static void main(String args[])
   {
      int m, n, p, q, sum = 0, c, d, k;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of rows and columns of first matrix");
      m = in.nextInt();
      n = in.nextInt();

      int first[][] = new int[m][n];

      System.out.println("Enter the elements of first matrix");

      for ( c = 0 ; c < m ; c++ )
         for ( d = 0 ; d < n ; d++ )
            first[c][d] = in.nextInt();

      System.out.println("Enter the number of rows and columns of second matrix");
      p = in.nextInt();
      q = in.nextInt();

      if ( n != p )
         System.out.println("Matrices with entered orders can't be multiplied with each other.");
      else
      {
         int second[][] = new int[p][q];
         int multiply[][] = new int[m][q];

         System.out.println("Enter the elements of second matrix");

         for ( c = 0 ; c < p ; c++ )
            for ( d = 0 ; d < q ; d++ )
               second[c][d] = in.nextInt();

         for ( c = 0 ; c < m ; c++ )
         {
            for ( d = 0 ; d < q ; d++ )
            {  
               for ( k = 0 ; k < p ; k++ )
               {
                  sum = sum + first[c][k]*second[k][d];
               }

               multiply[c][d] = sum;
               sum = 0;
            }
         }

         System.out.println("Product of entered matrices:-");

         for ( c = 0 ; c < m ; c++ )
         {
            for ( d = 0 ; d < q ; d++ )
               System.out.print(multiply[c][d]+"\t");

            System.out.print("\n");
         }
      }
   }
}

Hasilnya:


Monday, November 21, 2016

Mengubah Boolean jadi String

Codenya:

public class BooleanToString {
    public static void main(String[] args) {
       
        /* Method 1: using valueOf() method
         * of String class.
         */
        boolean boovar = true;
        String str = String.valueOf(boovar);
        System.out.println("String is: "+str);
       
        /* Method 2: using toString() method
         * of Boolean class
         */
        boolean boovar2 = false;
        String str2 = Boolean.toString(boovar2);
        System.out.println("String2 is: "+str2);
    }
}

Hasilnya:


Mengubah Double jadi String

Codenya

public class DoubleToString {
   public static void main(String[] args) {
       
       /* Method 1: using valueOf() method
        * of String class
        */
       double dvar = 101.11;
       String str = String.valueOf(dvar);
       System.out.println("String is: "+str);
       
       /* Method 2: using toString() method
        * of Double class
        */
       double dvar2 = 200.202;
       String str2 = Double.toString(dvar2);
       System.out.println("String2 is: "+str2);
   }
}

Hasilnya:


Mencari Nilai Terkecil dari Dua Angka

Codenya

public class FindMinimumOfTwoNumbersExample {

  public static void main(String[] args) {
 
 
    System.out.println(Math.min(34,45));
 
   
     System.out.println(Math.min(43.34f, 23.34f));

   
     System.out.println(Math.min(4324.334, 3987.342));
 
     System.out.println(Math.min(48092840,4230843));
  }
}

Hasilnya



Menghitung Luas Persegi

Codenya:

import java.util.Scanner;
class SquareAreaDemo {
   public static void main (String[] args)
   {
       System.out.println("Enter Side of Square:");
       //Capture the user's input
       Scanner scanner = new Scanner(System.in);
       //Storing the captured value in a variable
       double side = scanner.nextDouble();
       //Area of Square = side*side
       double area = side*side;
       System.out.println("Area of Square is: "+area);
   }
}

hasilnya:


Luas Segitiga

Codenya:

import java.util.Scanner;
class AreaTriangleDemo {
   public static void main(String args[]) {  
      Scanner scanner = new Scanner(System.in);

      System.out.println("Enter the width of the Triangle:");
      double base = scanner.nextDouble();

      System.out.println("Enter the height of the Triangle:");
      double height = scanner.nextDouble();

      //Area = (width*height)/2
      double area = (base* height)/2;
      System.out.println("Area of Triangle is: " + area);    
   }
}


Hasilnya:


Cek Bilangan Prima

Codenya;

import java.util.Scanner;
class PrimeCheck
{
   public static void main(String args[])
   {
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number for check:");
//capture the input in an integer
int num=scan.nextInt();
for(int i=2;i<=num/2;i++)
{
           temp=num%i;
  if(temp==0)
  {
     isPrime=false;
     break;
  }
}
//If isPrime is true then the number is prime else not
if(isPrime)
  System.out.println(num + " is Prime Number");
else
  System.out.println(num + " is not Prime Number");
   }
}

Hasilnya:


Menemukan Kuadrat suatu angka

Codenya

public class FindPowerExample {

  public static void main(String[] args) {
 
   
     System.out.println(Math.pow(2,2));
 
   
     System.out.println(Math.pow(-3,2));
  }
}

hasilnya:

Luas dan Keliling Lingkaran

import java.util.Scanner;
class CircleDemo
{
   static Scanner sc = new Scanner(System.in);
   public static void main(String args[])
   {
      System.out.print("Enter the radius: ");
      /*We are storing the entered radius in double
       * because a user can enter radius in decimals
       */
      double radius = sc.nextDouble();
      //Area = PI*radius*radius
      double area = Math.PI * (radius * radius);
      System.out.println("The area of circle is: " + area);
      //Circumference = 2*PI*radius
      double circumference= Math.PI * 2*radius;
      System.out.println( "The circumference of the circle is:"+circumference) ;
   }
}

hasilnya:

Palindrome Check

import java.util.Scanner;
class PalindromeCheck
{
    //My Method to check
    public static boolean isPal(String s)
    {   // if length is 0 or 1 then String is palindrome
        if(s.length() == 0 || s.length() == 1)
            return true;
        if(s.charAt(0) == s.charAt(s.length()-1))
        /* check for first and last char of String:
         * if they are same then do the same thing for a substring
         * with first and last char removed. and carry on this
         * until you string completes or condition fails
         * Function calling itself: Recursion
         */
        return isPal(s.substring(1, s.length()-1));

        /* If program control reaches to this statement it means
         * the String is not palindrome hence return false.
         */
        return false;
    }

    public static void main(String[]args)
    {
    //For capturing user input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the String for check:");
        String string = scanner.nextLine();
        /* If function returns true then the string is
         * palindrome else not
         */
        if(isPal(string))
            System.out.println(string + " is a palindrome");
        else
            System.out.println(string + " is not a palindrome");
    }
}

Hasilnya


Menampilkan Angka Prima

import java.util.Scanner;

class PrimeNumberDemo
{
   public static void main(String args[])
   {
      int n;
      int status = 1;
      int num = 3;
      //For capturing the value of n
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the value of n:");
      //The entered value is stored in the var n
      n = scanner.nextInt();
      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are:");
         //2 is a known prime number
         System.out.println(2);
      }

      for ( int i = 2 ; i <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            i++;
         }
         status = 1;
         num++;
      }        
   }
}


Hasilnya:


Thursday, November 17, 2016

HomeWork no. 7 Scanner

Jadi sekarang saya belajar menggunakan Library

Library adalah sekumpulan package atau koleksi kelas yang telah disediakan oleh Java. Untuk menggunakan Library dalam java kita menggunakan syntax import.

SCANNER

Scanner merupakan perintah untuk membuat objek atau menginisialisasi object yang diinginkan pengguna atau yang diinputkan pengguna




Sekarang saya mencoba untuk membuat program untuk menghitung luas dan keliling segitiga siku-siku dengan menggunakan library scanner.

Ini codenya:




Ini hasilnya :


Wednesday, November 16, 2016

HomeWork no. 6 Mengenal Overloading dan Overriding

Jumat lalu kita diberikan materi mengenai Overloading dan Overriding.

Overloading : Method Overloading adalah sebuah kemampuan yang membolehkan sebuah class mempunyai 2 atau lebih method dengan nama yang sama, yang membedakan adalah parameternya.

Overriding : Method overriding merupakan method yang parrent class yang ditulis kembali oleh subclass.


OVERRIDING

Kita juga diberikan tugas. Dalam tugas ini kita harus memerhatikan pembuatan classnya.

Kita akan membuat 3 kelas.

Yang pertama:

Kelas Binatang



Kelas Mamalia


Yang terakhir adalah Mainya



Hasilnya setelah semua terhubung



Program dijalankan


Sekian..


OVERLOADING

Method Overloading juga dikenal dengan sebutan Static Polymorphism. Berikut ini contoh Class yang melakukan Overloading.
Contoh dari overloading adalah
Gambaran dari source code

Codenya:


Hasilnya: