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:
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:
float double
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
Description
double abs(double d) float abs(float f) int abs(int i) long abs(long lng)
Returns the absolute value of the argument.
double ceil(double d)
Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
double floor(double d)
Returns the largest integer that is less than or equal to the argument. Returned as a double.
double rint(double d)
Returns the integer that is closest in value to the argument. Returned as a double.
long round(double d) int round(float f)
Returns the closest long or int, as indicated by the method's return type, to the argument.
double min(double arg1, double arg2) float min(float arg1, float arg2) int min(int arg1, int arg2) long min(long arg1, long arg2)
Returns the smaller of the two arguments.
double max(double arg1, double arg2) float max(float arg1, float arg2) int max(int arg1, int arg2) long max(long arg1, long arg2)
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
Description
double exp(double d)
Returns the base of the natural logarithms, e, to the power of the argument.
double log(double d)
Returns the natural logarithm of the argument.
Returns the value of the first argument double pow(double base, double exponent) raised to the power of the second argument. double sqrt(double d)
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
Description
double sin(double d)
Returns the sine of the specified double value.
double cos(double d)
Returns the cosine of the specified double value.
double tan(double d)
Returns the tangent of the specified double value.
double asin(double d)
Returns the arcsine of the specified double value.
double acos(double d)
Returns the arccosine of the specified double value.
double atan(double d)
Returns the arctangent of the specified double value.
double atan2(double y, double x)
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.
double toDegrees(double d) double toRadians(double d)
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
Description
Returns a new string that is a substring of this string. String substring(int beginIndex, The first integer argument specifies the index of the int endIndex) 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 String substring(int beginIndex) 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
Description
Searches for a match as specified by the string argument (which contains a regular expression) and splits this string String[] split(String regex) into an array of strings accordingly. The optional integer String[] split(String regex, argument specifies the maximum size of the returned array. int limit) Regular expressions are covered in the lesson titled "Regular Expressions." CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence constructed from beginIndex index up until endIndex - 1.
String trim()
Returns a copy of this string with leading and trailing white space removed.
String toLowerCase() String toUpperCase()
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
Description
int indexOf(int ch) int lastIndexOf(int ch)
Returns the index of the first (last) occurrence of the specified character.
int indexOf(int ch, int fromIndex) int lastIndexOf(int ch, int fromIndex)
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
int indexOf(String str) int lastIndexOf(String str)
Returns the index of the first (last) occurrence of the specified substring.
int indexOf(String str, int fromIndex) int lastIndexOf(String str, int fromIndex)
Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index.
boolean contains(CharSequence s)
Returns true if the string contains the specified character sequence.
Replacing Characters and Substrings into a String Method
Description
Returns a new string resulting from String replace(char oldChar, char newChar) replacing all occurrences of oldChar in this string with newChar. String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String 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
Description
Returns true if this string ends with or begins with boolean endsWith(String suffix) the substring specified as an argument to the boolean startsWith(String prefix) method. Considers the string beginning at the index offset, boolean startsWith(String prefix, and returns true if it begins with the substring int offset) specified as an argument. int compareTo(String anotherString)
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.
int compareToIgnoreCase(String str)
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
Description
boolean equals(Object anObject)
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 boolean equalsIgnoreCase(String represents the same sequence of characters as this object, anotherString) ignoring differences in case. boolean regionMatches(int toffset, String other, int ooffset, int len)
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 boolean regionMatches(boolean and begins at the index toffset for this string and ooffset for the ignoreCase, int toffset, String other string. other, int ooffset, int len) The boolean argument indicates whether case should be ignored; if true, case is ignored when comparing characters.
boolean matches(String regex)
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. 2.
3. 4.
Array declaration Array creation Array initialization Array processing
1. Array Declaration: [ ]
Kita dapat mendeklarasikan sebuah variabel array bertipe apapun Contoh Deklarasi Array: String[] students; int[] values; boolean[] truthTable; char[] grades;
// // // //
An An An An
array array array array
of of of of
String variables integer variables boolean variables 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(){ Parameter berupa array 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; private static void tampilkanArray(int[ ] arr){ } System.out.println(" == ISI DARI ARRAY == "); return arrayInputan; for (int i = 0; i < arr.length; i++){ } System.out.println("Isi dari element ke: " + i + " adalah // continue… " + 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]
Column: Row: 0 1 2
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
Margaret
Frank
Nathan
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