Pertemuan 4 Number, Character, String & Array Processing BS205 Pemrograman Berorientasi Objek Niko Ibrahim, S.Kom, MIT
1. Numbers in Java Primitives types Operators and Expressions Mixed types Math Class Number Class
Primitive Types Java memiliki beberapa primitive types yang bersifat built-in, dan tidak memerlukan pendefinisian kelas untuk menggunakannya. Primitive Types tersebut dapat berupa: karakter (char) bilangan bulat (int) bilangan desimal (float) Primitive Types bukanlah Objek!, sehingga tidak memiliki atribut, method, ataupun constructor. Beberapa primitive types yang sering dipakai: numeric types: byte, short, int, long, float, double non-numeric types: char, boolean (more later...)
Integers Bilangan bulat (Integer) di Java dapat berupa salah satu berikut: byte short int long Yang paling umum dipakai adalah int Bilangan integer tidak boleh ada spasi ataupun koma Contoh: 1001-25 Tipe byte dan short jarang digunakan
Real (Floating Point Number) Bilangan desimal atau pecahan seringkali disebut sebagai Real atau floating-point numbers. Ada dua jenis bilangan Real, yaitu: float double Yang paling umum dipakai adalah double Bilangan pecahan disimpan dengan tingkat akurasi yang terbatas Operasi aritmatika terhadap bilangan pecahan menghasilkan nilai pendekatan Contoh bilangan desimal: 23.89 0.0032 Dapat menggunakan notasi ilmiah E Contoh: 5100 = 5.1E+3 0.221 = 2.2e-2
Tabel Tipe Bilangan Type Storage Min Value Max Value byte 8 bits -128 127 short 16 bits -32,768 32,768 int 32 bits -2,147,483,648 2,147,483,647 long 64 bits -9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 32 bits approx. -3.4E+38 approx. 3.4E+38 double 64 bits approx. -1.7E+308 approx. 1.7E+308
Konstanta Konstanta atau constant (seringkali disebut juga literals) adalah variabel yang hanya di-assign sekali Untuk mendefinisikan konstanta di Java, kita gunakan kata final Contoh: final float PI = 3.14159; final int LIFE = 42; Konstanta digunakan untuk menyimpan nilai yang tidak boleh diubah di dalam program Konstanta juga membuat kode program lebih mudah dibaca Apabila perlu pengubahan nilai konstanta, cukup diubah di satu tempat yaitu pada tempat pendefinisian konstanta tersebut (change only in one spot) Biasanya konstanta dituliskan dengan huruf besar semua, misal: MAX_LOAD, LIFE_TIME, PI, dll.
MIXED TYPES Two or more different numeric types involved Example: 12 + 7.04 =? safe conversions widening: no information lost (wider type value can represent any narrower type value) Java uses automatic widening: of all the types used in the expression, the results type is the last type (reading left to right) on the list: int < long < float < double Example: 7.0/2 evaluates as 7.0/2.0 producing double double + float = double no automatic narrowing (unsafe! lost of data/precision) - can only be forced, using for example casting
Casting casting (forced conversion) - adalah suatu cara untuk memaksa perubahan tipe Dengan melakukan casting, kita mungkin akan kehilangan informasi (misalnya adanya penhapusan nilai pecahan di belakang koma) Sintaks: (type) expression Contoh: nilai = (int) 12.78; mengasilkan: nilai = 12; Contoh lain: int i = 5.5; // illegal! (5.5 is a float type number, not an integer) casting must be used - otherwise the compiler will produce error Cara yang benar adalah: int i = (int)5.5;
Contoh: Swapping Pattern public class Swap { public Swap(){ private int x = 26; private int y = 45 ; //print out some values or messages System.out.println("Before swapping..."); System.out.println("x = " + x +", y = " + y) ; // the 'swap' pattern int temp ; //need a temporary storage temp = x ; x = y ; y = temp ; //print it out again to see the difference System.out.println("After swapping..."); System.out.println("x = " + x +", y = " + y) ;
Output
Brain Teaser 1: Analyse This
Brain Teaser 2: What value?
Circular Counting Problem Anda memerlukan sebuah variabel untuk menghitung bilangan secara terurut berdasarkan range tertentu dari range paling rendah ke range paling tinggi. Penghitungan terus berulang, artinya saat penghitungan mencapai range tertinggi, maka akan kembali menghitung dari range yang terendah. Misal: range 1 s/d 5, step = 1 Circular Counting: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, dst. Solution The simplest case (which is also quite common) is when the sequence begins at 0, has a step size of 1, and contains n values (which means that the range is 0 to n-1). In this case, compute the new value for the variable using the assignment: v = (v + 1) % n; As long as v+1 remains less than n, the remainder when it is divided by n will be the same value, thus ensuring that the successive values will increase by one each time. But when v reaches n - 1 (the final value in the sequence), v+1 will equal n and the remainder (and hence the next value) will be zero. In the general case, the new value for the variable is given by the assignment: v = min + (v - min + step) % (max - min + 1) where max and min are the largest and smallest values in the sequence and step is the step size.
Brain Teaser: What is the output? Formula: v = min + (v - min + step) % (max - min + 1) Starting from: v = 4 min = 3 max = 20 step = 5 Result:? 9,14,19,6,11,16,3,8,13,18,5,10,15,20,7,12,17,4, 9,14,19,6,11,16,3,8,13,18,5,10,15,20,7,12,17,4, 9,14,19,6,11,...
Testing Code public class circular{ private int v,min,max,step; public circular() { // initialise instance variables v = 4; min = 3; max = 20; step = 5; for (int i = 0; i <= 40; i++){ v = min + (v - min + step) % (max - min + 1); System.out.print(v + ",");
Math Class Java memiliki standard library yang berhubungan dengan operasi matematika, yang disimpan dan dikelompokkan ke dalam kelas MATH (MATH CLASS) Kelas MATH ini memiliki method-method yang umum sekali digunakan untuk melakukan perhitungan matematika Beberapa penggunaan kelas MATH: Konstanta: Math.E, Math.PI Rumus matematika dasar (basic methods) Ekponensial & logaritmic Trigonometri Random Penggunaan: import static java.lang.math.*; abs(-10) floor(5.8)
Math Class Methods Method double abs(double d) float abs(float f) int abs(int i) long abs(long lng) double ceil(double d) double floor(double d) double rint(double d) long round(double d) int round(float f) double min(double arg1, double arg2) float min(float arg1, float arg2) int min(int arg1, int arg2) long min(long arg1, long arg2) double max(double arg1, double arg2) float max(float arg1, float arg2) int max(int arg1, int arg2) long max(long arg1, long arg2) Description Returns the absolute value of the argument. Returns the smallest integer that is greater than or equal to the argument. Returned as a double. Returns the largest integer that is less than or equal to the argument. Returned as a double. Returns the integer that is closest in value to the argument. Returned as a double. Returns the closest long or int, as indicated by the method's return type, to the argument. Returns the smaller of the two arguments. Returns the larger of the two arguments.
BasicMathDemo.java public class BasicMathDemo { public static void main(string[] args) { double a = -191.635; double b = 43.74; int c = 16, d = 45; System.out.printf("The absolute value " + "of %.3f is %.3f%n", a, Math.abs(a)); System.out.printf("The ceiling of " + "%.2f is %.0f%n", b, Math.ceil(b)); System.out.printf("The floor of " + "%.2f is %.0f%n", b, Math.floor(b)); System.out.printf("The rint of %.2f " + "is %.0f%n", b, Math.rint(b)); System.out.printf("The max of %d and " + "%d is %d%n", c, d, Math.max(c, d)); System.out.printf("The min of of %d " + "and %d is %d%n", c, d, Math.min(c, d));
Exponential and Logarithmic Methods Method double exp(double d) double log(double d) double pow(double base, double exponent) double sqrt(double d) Description Returns the base of the natural logarithms, e, to the power of the argument. Returns the natural logarithm of the argument. Returns the value of the first argument raised to the power of the second argument. Returns the square root of the argument.
ExponentialDemo.java public class ExponentialDemo { public static void main(string[] args) { double x = 11.635; double y = 2.76; System.out.printf("The value of " + "e is %.4f%n", Math.E); System.out.printf("exp(%.3f) " + "is %.3f%n", x, Math.exp(x)); System.out.printf("log(%.3f) is " + "%.3f%n", x, Math.log(x)); System.out.printf("pow(%.3f, %.3f) " + "is %.3f%n", x, y, Math.pow(x, y)); System.out.printf("sqrt(%.3f) is " + "%.3f%n", x, Math.sqrt(x));
Trigonometry Methods Method double sin(double d) double cos(double d) double tan(double d) double asin(double d) double acos(double d) double atan(double d) double atan2(double y, double x) double todegrees(double d) double toradians(double d) Description Returns the sine of the specified double value. Returns the cosine of the specified double value. Returns the tangent of the specified double value. Returns the arcsine of the specified double value. Returns the arccosine of the specified double value. Returns the arctangent of the specified double value. Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta. Converts the argument to degrees or radians.
TrigonometricDemo.java public class TrigonometricDemo { public static void main(string[] args) { double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi " + "is %.4f%n", Math.PI); System.out.format("The sine of %.1f " + "degrees is %.4f%n", degrees, Math.sin(radians)); System.out.format("The cosine of %.1f " + "degrees is %.4f%n", degrees, Math.cos(radians)); System.out.format("The tangent of %.1f " + "degrees is %.4f%n", degrees, Math.tan(radians)); System.out.format("The arcsine of %.4f " + "is %.4f degrees %n", Math.sin(radians), Math.toDegrees(Math.asin(Math.sin(radians)))); System.out.format("The arccosine of %.4f " + "is %.4f degrees %n", Math.cos(radians), Math.toDegrees(Math.acos(Math.cos(radians)))); System.out.format("The arctangent of %.4f " + "is %.4f degrees %n", Math.tan(radians), Math.toDegrees(Math.atan(Math.tan(radians))));
Random Numbers The random() method returns a pseudo-randomly selected number between 0.0 and 1.0. The range includes 0.0 but not 1.0. In other words: 0.0 <= Math.random() < 1.0. To get a number in a different range, you can perform arithmetic on the value returned by the random method. For example, to generate an integer between 0 and 9, you would write: int number = (int)(math.random() * 10); By multiplying the value by 10, the range of possible values becomes 0.0 <= number < 10.0. Using Math.random works well when you need to generate a single random number. If you need to generate a series of random numbers, you should create an instance of java.util.random and invoke methods on that object to generate numbers.
Random Numbers (cont.) Case: You need to generate a number that lies within a specified range, but whose actual value is unpredictable. Every time you generate the number, you expect to get a different result. Solution: 1 + (int)(math.random() * n); //integer within the range 1..n min + Math.random() * (max - min) //float in range min..max To generate an unpredicable integer value in the range min to max, use the expression: min + (int)(math.random() * (max - min + 1)) Since the Math.random() method returns a floating point value between 0 and 1, the right-hand parenthesis produces a floating point value between 0 and (max-min+1). Casting this value to an int throws away any fractional component, thus producing an integer in the range 0 to max-min, which means that the overall value is in the range min to max.
Contoh: Randomizer.java public class random { private int v, min=10, max=25; public random() { for (int i = 0; i <= 10; i++){ //generate random number: v = min + (int)(math.random()*(max-min + 1)); //print the random numbers: System.out.print(v + ", "); Result Example(could be different for each runs): 11, 21, 18, 14, 12, 22, 12, 11, 13, 20, 18,
2. Characters Most of the time, if you are using a single character value, you will use the primitive char type. For example: char ch = 'a'; // Unicode for uppercase Greek omega character char unichar = '\u03a9'; // an array of chars char[] chararray = { 'a', 'b', 'c', 'd', 'e' ;
Escape Sequences Escape Sequence Description \t Insert a tab in the text at this point. \b Insert a backspace in the text at this point. \n Insert a newline in the text at this point. \r Insert a carriage return in the text at this point. \f Insert a formfeed in the text at this point. \' Insert a single quote character in the text at this point. \" Insert a double quote character in the text at this point. \\ Insert a backslash character in the text at this point. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence: She said "Hello!" to me. You would write: System.out.println("She said \"Hello!\" to me.");
3. Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. Creating Strings String greeting = "Hello world!"; char[] helloarray = { 'h', 'e', 'l', 'l', 'o', '.' ; String hellostring = new String(helloArray); System.out.println(helloString);
String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17: String palindrome = "Dot saw I was Tod"; int len = palindrome.length();
StringDemo.java: palindrom To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getchars(), to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with palindrome.getchars(0, len, tempchararray, 0);
StringDemo.java (Palindrom) public class StringDemo { public static void main(string[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempchararray = new char[len]; char[] chararray = new char[len]; // put original string in an // array of chars for (int i = 0; i < len; i++) { tempchararray[i] = palindrome.charat(i); // reverse array of chars for (int j = 0; j < len; j++) { chararray[j] = tempchararray[len - 1 - j]; String reversepalindrome = new String(charArray); System.out.println(reversePalindrome);
Concatenating Strings The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in: "My name is ".concat("rumplestiltskin"); Strings are more commonly concatenated with the + operator, as in "Hello," + " world" + "!" which results in "Hello, world!"
Getting Characters and Substrings by Index You can get the character at a particular index within a string by invoking the charat() accessor method. The index of the first character is 0, while the index of the last character is length()-1. For example, the following code gets the character at index 9 in a string: String anotherpalindrome = "Niagara. O roar again!"; char achar = anotherpalindrome.charat(9); Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:
The substring Methods in the String Class Method String substring(int beginindex, int endindex) String substring(int beginindex) Description Returns a new string that is a substring of this string. The first integer argument specifies the index of the first character. The second integer argument is the index of the last character - 1. Returns a new string that is a substring of this string. The integer argument specifies the index of the first character. Here, the returned substring extends to the end of the original string. The following code gets from the Niagara palindrome the substring that extends from index 11 up to, but not including, index 15, which is the word "roar": String anotherpalindrome = "Niagara. O roar again!"; String roar = anotherpalindrome.substring(11, 15);
Other Methods for Manipulating Strings Method String[] split(string regex) String[] split(string regex, int limit) CharSequence subsequence(int beginindex, int endindex) String trim() String tolowercase() String touppercase() Description Searches for a match as specified by the string argument (which contains a regular expression) and splits this string into an array of strings accordingly. The optional integer argument specifies the maximum size of the returned array. Regular expressions are covered in the lesson titled "Regular Expressions." Returns a new character sequence constructed from beginindex index up until endindex - 1. Returns a copy of this string with leading and trailing white space removed. Returns a copy of this string converted to lowercase or uppercase. If no conversions are necessary, these methods return the original string.
Searching for Characters and Substrings in a String Method int indexof(int ch) int lastindexof(int ch) int indexof(int ch, int fromindex) int lastindexof(int ch, int fromindex) int indexof(string str) int lastindexof(string str) int indexof(string str, int fromindex) int lastindexof(string str, int fromindex) boolean contains(charsequence s) Description Returns the index of the first (last) occurrence of the specified character. Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index. Returns the index of the first (last) occurrence of the specified substring. Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index. Returns true if the string contains the specified character sequence.
Replacing Characters and Substrings into a String Method String replace(char oldchar, char newchar) String replace(charsequence target, CharSequence replacement) String replaceall(string regex, String replacement) String replacefirst(string regex, String replacement) Description Returns a new string resulting from replacing all occurrences of oldchar in this string with newchar. Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. Replaces each substring of this string that matches the given regular expression with the given replacement. Replaces the first substring of this string that matches the given regular expression with the given replacement.
Comparing Strings and Portions of Strings Method boolean endswith(string suffix) boolean startswith(string prefix) boolean startswith(string prefix, int offset) int compareto(string anotherstring) int comparetoignorecase(string str) Description Returns true if this string ends with or begins with the substring specified as an argument to the method. Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument. Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument. Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
Comparing Strings and Portions of Strings (cont) Method boolean equals(object anobject) boolean equalsignorecase(string anotherstring) boolean regionmatches(int toffset, String other, int ooffset, int len) boolean regionmatches(boolean ignorecase, int toffset, String other, int ooffset, int len) boolean matches(string regex) Description Returns true if and only if the argument is a String object that represents the same sequence of characters as this object. Returns true if and only if the argument is a String object that represents the same sequence of characters as this object, ignoring differences in case. Tests whether the specified region of this string matches the specified region of the String argument. Region is of length len and begins at the index toffset for this string and ooffset for the other string. Tests whether the specified region of this string matches the specified region of the String argument. Region is of length len and begins at the index toffset for this string and ooffset for the other string. The boolean argument indicates whether case should be ignored; if true, case is ignored when comparing characters. Tests whether this string matches the specified regular expression. Regular expressions are discussed in the lesson titled "Regular Expressions."
RegionMatchesDemo.java public class RegionMatchesDemo { public static void main(string[] args) { String searchme = "Green Eggs and Ham"; String findme = "Eggs"; int searchmelength = searchme.length(); int findmelength = findme.length(); boolean foundit = false; for (int i = 0; i <= (searchmelength - findmelength); i++) { if (searchme.regionmatches(i, findme, 0, findmelength)) { foundit = true; System.out.println(searchMe.substring(i, i + findmelength)); break; if (!foundit) System.out.println("No match found.");
4.Array Array adalah variabel yang yang dikelompokkan bersama dalam suatu nama. Sama seperti variabel, array pun dibuat dengan cara menyebutkan tipe data dan nama array-nya. Perbedaannya adalah adanya penambahan tanda bracket [ dan ]. Array memiliki panjang yang fixed. Sekali didefinisikan, panjangnya akan tetap sama. Namun, suatu variabel array dapat di-reassign sedemikian rupa sehingga ia mengacu pada array baru yang memiliki panjang yg berbeda.
Contoh Representasi Array Nama array: c Tipe array: int Panjang array: 12
Ada 4 Tahap Manipulasi Array 1. Array declaration 2. Array creation 3. Array initialization 4. Array processing
1. Array Declaration: [ ] Kita dapat mendeklarasikan sebuah variabel array bertipe apapun Contoh Deklarasi Array: String[] students; int[] values; // An array of String variables // An array of integer variables boolean[] truthtable; // An array of boolean variables char[] grades; // An array of character variables Kita juga dapat menuliskan tanda [ ] setelah nama variabel seperti berikut: String students[]; Jadi, String[] students === String students[]
2. Array Creation: new Untuk membuat sebuah array, kita dapat menggunakan keyword new dan sekaligus menentukan panjang array tersebut, sbb: String[] names; names = new String[10]; // deklarasi array // create array Kita dapat juga menkombinasikan deklarasi dan create ini menjadi satu statement sbb: String[] names = new String[10];
3. Array Initialization: { One way to initialize the values in an array is to simply assign them one by one: String[] days = new String[7]; days[0] = "Sunday"; days[1] = "Monday"; days[2] = "Tuesday"; days[3] = "Wednesday"; days[4] = "Thursday"; days[5] = "Friday"; days[6] = "Saturday"; Java has a shorthand way to create an array and initialize it with constant values: String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ;
Contoh inisialisasi array berisi integer Berikut contoh untuk menginisialisasi array integer: int[] primes = { 2, 3, 5, 7, 11, 13, 17 ; Alternatif lain adalah sbb: int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17 ;
4.1 Pemrosesan Array: for loop Cara yang paling umum dalam memproses array adalah dengan menggunakan for-loop. Setiap array memiliki atribut length yang dapat kita manfaatkan sebagai titik akhir dari for-loop tersebut. Contoh: int[ ] arraynilai = new int[10]; for (int i = 0; i < arraynilai.length; i++{ // loop ini akan diulang 10x Untuk mengambil suatu elemen di dalam array tersebut, kita dapat manfaatkan nilai counter i, sbb: int nilaiyangdiambil = arraynilai[i];
Latihan Array 1: Days.java public class Days{ public static void main(string[] args){ String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday" ; for (int i = 0; i < days.length; i++){ System.out.println(days[i]);
4.2 Pemrosesan Array Menggunakan Enhanced for loop (foreach) Selain menggunakan for-loop, kita juga dapat menggunakan enhanced for-loop yang secara khusus dirancang untuk digunakan pada array dan collections. Enhanced for-loop ini biasa juga disebut dengan nama foreach loop karena cara kerjanya yang memproses each element di dalam array. Sintaksnya sbb: for (type variablename : arrayname){ // statements
Latihan Array 2: Days2.java Menggunakan foreach loop public class Days2{ public static void main(string[] args){ String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday" ; for (String dayelement: days){ System.out.println(dayElement);
Latihan Array 3: SumArray.java Kita dapat melakukan operasi aritmatika kepada elemen (isi) array yang bertipe angka (int, float, dll). public class SumArray { public static void main( String args[] ) { int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 ; int total = 0; // add each element's value to total for ( int counter = 0; counter < array.length; counter++ ){ total = total + array[ counter ]; System.out.printf( "Total of array elements: %d\n", total );
Latihan Array 4: SumArrayEnhanced.java Menggunakan foreach-loop public class SumArrayEnhanced { public static void main( String args[] ){ int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 ; int total = 0; // add each element's value to total for ( int number : array ) total += number; System.out.printf( "Total of array elements: %d\n", total ); // end main // end class SumArrayEnhanced
Array sebagai parameter dan return type Kita dapat menjadikan array sebagai parameter untuk suatu method ataupun sebagai return type dari suatu method Misalnya, kita ingin membuat static method yang berfungsi untuk menerima 5 input angka yang akan disimpan ke dalam sebuah array. private static int[] inputarray(){ // meminta input dari user untuk disimpan ke dalam array // return array tersebut Kemudian, kita juga ingin membuat sebuah static method yang menerima parameter berupa array. Fungsi method ini adalah untuk menampilkan hasil input dari user tersebut. private static void tampilkanarray(int[] arrparameter){ // proses arrparameter tersebut
Latihan Array 5: ArrayPassing.java import java.util.scanner; public class ArrayPassing{ public static void main(string[ ] args){ System.out.println("Program Input dan Output Array"); int[ ] arrayinputan = inputarray(); tampilkanarray(arrayinputan); Return type berupa array private static int[ ] inputarray(){ int[ ] arrayinputan = new int[5]; Scanner sc = new Scanner(System.in); // Minta input sebanyak 5 kali: for (int i = 0; i < 5; i++){ System.out.print("Inputlah element ke-" + i + ": "); int nilaielement = sc.nextint(); arrayinputan[i] = nilaielement; return arrayinputan; // continue Parameter berupa array private static void tampilkanarray(int[ ] arr){ System.out.println(" == ISI DARI ARRAY == "); for (int i = 0; i < arr.length; i++){ System.out.println("Isi dari element ke: " + i + " adalah " + arr[i]);
Two Dimensional Array Multidimensional arrays berdimensi 2 sering digunakan untuk merepresentasikan tabel berisi nilai di dalam kolom dan baris. Untuk menentukan element suatu sel tabel tersebut, kita harus menyebutkan dua index, yaitu untuk baris dan kolom. Sintaks: type[][] arrayname = new type[rowcount][columncount]; Examples: int[][] numbers = new int[3][2]; // array creation int[][] numbers = {{1,2,{3,4,{5,6; Ilustration: int [3][2] Row: 0 1 2 Column: 0 1 0,0 0,1 1,0 1,1 2,0 2,1
Latihan 6: Init2DArray.java public class Init2DArray { public static void main( String args[] ){ int numbers[][] = { { 1, 2, 3, { 4, 5, 6 ; System.out.println( "Values in array by row are" ); for ( int row = 0; row < numbers.length; row++ ){ System.out.print("Row " + row + ": "); for (int column = 0; column < numbers[row].length; column++){ System.out.print(numbers[ row ][ column ] ); // end inner for System.out.println(); // start new line of output // end outer for // end of main
Jagged Array Jagged array adalah suatu array 2 dimensi, yang jumlah barisnya berbeda dengan jumlah kolomnya. Untuk membuat jagged array, kita hanya perlu menentukan jumlah baris-nya saja. Contoh Pembuatan Jagged Array: int[][] numbers = new int[3][]; // baris = 3 String[][] teams = { {"Henry", "Johnny", // 2 col {"Ben", "John", "Nathan",// 3 col {"Margaret", "Frank", // 2 col ; Henry Johnny Ben John Nathan Margaret Frank
Latihan 7: JaggedArray.java public class JaggedArray{ public static void main( String args[] ){ int number = 0; // Create and initialize a jagged array int[][] pyramid = new int[4][]; for (int row = 0; row < pyramid.length; row++){ pyramid[row] = new int[row+1]; for (int col = 0; col < pyramid[row].length; col++){ pyramid[row][col] = number++; // print the contents of the jagged array: for (int row = 0; row < pyramid.length; row++){ for (int col = 0; col < pyramid[row].length; col++){ System.out.print(pyramid[row][col] + " "); System.out.println(); // end main // end class JaggedArray
Using Command Line Arguments Kita dapat memberikan suatu parameter kepada program pada saat di-run. Parameter ini dikenal sebagai command-line arguments. Parameter yang kita berikan sebenarnya merupakan array String public static void main( String args[] ){ // statements Biasanya, parameter ini kita namakan args. Pada saat aplikasi di-run dengan menggunakan perintah java, maka compiler Java akan mengirimkan parameter args tersebut sebagai array yang berisi String. Jumlah parameter yang diberikan kepada compiler dapat diketahui melalui atribut length. Misalnya, kita me-run program myclass sebagai berikut: C:> java MyClass a b Pada saat perintah di atas dieksekusi, method main dari MyClass akan menerima array args yang berisi 2 elemen. Berikut ini adalah data yang kita dapatkan: args.length = 2 args[0] = "a" args[1] = "b"
Latihan 8: ArgumentsDemo.java public class ArgumentsDemo{ public static void main( String args[] ){ int length = args.length; System.out.println("Number of arguments: " + length); for (int i = 0; i < length; i++){ System.out.print ("Argument No: " + i); System.out.println (" --> " + args[i]);
NEXT LECTURE Object & Class Intro to BlueJ