CHAPTER #3
Method, Array dan String
3.1. Method
3.1.1. Pengenalan Method
Method adalah bagian dari tubuh program yang mengimplementasikan suatu action sehingga class atau object dapat bekerja. Method diimplementasikan didalam class dan menyediakan informasi tambahan yang mana class tidak dapat menangani sendiri.
Method dideklarasikan dengan format sebagai berikut
Modifier sifat return_type nama_method (parameter)
ModifierModifier adalah keyword yang digunakan untuk menspesifikasi deklarasi pengaksesan suatu member atau tipe.
Ada 4 modifier pengaksesan yaitu :
• public
• protected
• internal
• private
Tabel 2.1. Modifier dan Hak Aksesnya Level akses Arti
Public Akses tidak dibatasi
protected Akses dibatasi pada classnya saja atau tipe yang diturunkan dari class
internal Akses hanya dibatasi pada satu project yang sama private Akses dibatasi pada tipe
Dengan ke empat level akses ini, method dapat diberikan pembatasan-pembatasan pengaksesan. Jika methods yang kita buat hanya ingin diakses pada project tertentu, maka kita bisa memberikan modifier internal.
Sifat
Sifat dari Method dapat terdiri dari static atau non-static. Method static adalah method yang hanya dapat di akses dari class. Sedangkan method Non-static dapat di akses dari instancesnya saja.
Return_type
Return_Type adalah nilai pengembalian dari suatu method. Apabila method tidak mengembalikan suatu nilai, maka return_type nya didefinisikan dengan void.
Parameter
Parameter adalah nilai yang diparsingkan ke suatu method. Method dapat memiliki lebih dari 1 parameter, atau bisa juga tidak memiliki parameter. Parameter dideklarasikan dengan menentukan type dari variabel yang digunakan serta nama variabel.
Contoh
using System; class Exercise {
static char HaveCharacter() {
return 'G'; }
static void Main() { Console.Write("Character: "); Console.WriteLine(HaveCharacter()); Console.ReadLine(); } } Hasil eksekusi Character: G using System; using System.Collections.Generic; using System.Text; namespace Geometry1 {
public class Lingkaran
{
public double GetRadius() {
double rad;
Console.Write("Radius: ");
rad = double.Parse(Console.ReadLine()); return rad;
}
public double CalculateBaseArea(double rad) {
return rad * rad * Math.PI; }
public static void Main() {
double Radius, BaseArea;
Lingkaran a = new Lingkaran();
Console.WriteLine("Masukkan jari jari lingkaran : "); Radius = a.GetRadius();
BaseArea = a.CalculateBaseArea(Radius); Console.WriteLine("\nLingkaran dengan "); Console.WriteLine("Radius: {0}", Radius); Console.WriteLine("Luas: {0:F}", BaseArea); Console.Read();
} } }
3.1.2. Passing Parameter pada method
Dalam method terdapat dua cara untuk mempassingkan parameter yaitu 1. passing parameter by value dan
2. Passing parameter by reference Passing parameter by value
Passing parameter by value hanya akan mempassingkan nilai ke dalam method, variabel yang dipassingkan akan dibuat secara lokal didalam method.
Contoh
using System;
public class Payroll {
static void Earnings(double ThisWeek, double Salary) {
ThisWeek = 42.50;
Console.WriteLine("\nIn the Earnings() function,"); Console.Write("Weekly Hours = "); Console.WriteLine(ThisWeek); Console.Write("Salary = "); Console.WriteLine(Salary); Console.Write("Weekly Salary: = "); Console.WriteLine(ThisWeek * Salary); }
static int Main() {
double Hours, Rate; Rate = 15.58;
Hours = 26.00;
Console.WriteLine("In the Main() method,"); Console.Write("\nWeekly Hours = "); Console.Write(Hours); Console.Write("\nSalary = "); Console.WriteLine(Rate); Console.Write("Weekly Salary = "); Console.WriteLine(Hours * Rate);
Console.WriteLine("\nCalling the Earnings() method"); Earnings(Hours, Rate);
Console.Write("\nAfter calling the Earnings() method, "); Console.WriteLine("\nin the Main() function,");
Console.Write("\nWeekly Hours = "); Console.Write(Hours); Console.Write("\nSalary = "); Console.WriteLine(Rate); Console.Write("Weekly Salary = "); Console.WriteLine(Hours * Rate); Console.Write("\n"); return 0; } }
Hasil sewaktu dieksekusi: In the Main() method, Weekly Hours = 26 Salary = 15.58 Weekly Salary = 405.08
Calling the Earnings() method In the Earnings() function, Weekly Hours = 42.5 Salary = 15.58 Weekly Salary: = 662.15
After calling the Earnings() method, in the Main() function,
Weekly Hours = 26 Salary = 15.58 Weekly Salary = 405.08
Dari sini dapat dilihat bahwa nilai variabel sebelum dan sesudah pemanggilan method Earnings masih bernilai sama. Hal ini disebabkan karena yang diparsingkan adalah nilai parameter.
Cara lain untuk mempassingkan parameter tetapi nilai yang dipassingkan setelah keluar dari method juga berubah adalah dengan menggunakan keyword out. Keyword out akan mengembalikan nilai yang diubah di dalam method.
Contoh
using System; class Exercise
{
static void Initializer(out double n) {
n = 128.44; }
public static int Main() {
double Number = 15.25;
Console.WriteLine("Number = {0}", Number); Initializer(out Number);
Console.WriteLine("Number = {0}", Number); Console.Read();
return 0; }
}
Passing parameter by reference
Passing parameter by reference akan mempassingkan alamat variabel di dalam memori ke method yang dipanggilnya. Dengan demikian apabila variabel tersebut
diubah di dalam method, maka variabel yang dipassingkan akan berubah, karena variabel yang berada di dalam method memiliki alamat yang sama dengan alamat variabel yang dipassingkan. Untuk mempassingkan parameter dengan reference digunakan keyword ref.
Contoh using System; using System.Collections.Generic; using System.Text; namespace Geometry1 { class Cylinder {
public void GetRadius(ref double rad) {
Console.Write("Radius: ");
rad = double.Parse(Console.ReadLine()); }
public void GetHeight(out double h) {
Console.Write("Height: ");
h = double.Parse(Console.ReadLine()); }
public double CalculateBaseArea(double rad) {
return rad * rad * Math.PI; }
public double CalculateLateralArea(double rad, double hgt) {
return 2 * Math.PI * rad * hgt; }
public double CalculateTotalArea(double rad, double hgt) {
return 2 * Math.PI * rad * (hgt + rad); }
public double CalculateVolume(double rad, double hgt) {
return Math.PI * rad * rad * hgt; }
public static void Main() { double Radius = 0.00; double Height = 0.00; double BaseArea; double LateralArea; double TotalArea; double Volume;
Cylinder tabung = new Cylinder();
Console.WriteLine("Enter the dimensions of the cylinder"); tabung.GetRadius(ref Radius);
tabung.GetHeight(out Height);
BaseArea = tabung.CalculateBaseArea(Radius);
LateralArea = tabung.CalculateLateralArea(Radius, Height); TotalArea = tabung.CalculateTotalArea(Radius, Height); Volume = tabung.CalculateVolume(Radius, Height);
Console.WriteLine("\nCylinder Characteristics"); Console.WriteLine("Radius: {0}", Radius);
Console.WriteLine("Height: {0}", Height); Console.WriteLine("Base: {0:F}", BaseArea); Console.WriteLine("Lateral: {0:F}", LateralArea); Console.WriteLine("Total: {0:F}", TotalArea); Console.WriteLine("Volume: {0:F}", Volume); Console.Read();
} } }
Hasil Eksekusi:
Enter the dimensions of the cylinder Radius: 24.55 Height: 20.85 Cylinder Characteristics Radius: 24.55 Height: 20.85 Base: 1893.45 Lateral: 3216.16 Total: 7003.05 Volume: 39478.34
3.2. Array
Array dapat dianggap suatu kumpulan variabel yang memiliki tipe data yang sama. Array termasuk dalam tipe data reference. Karena itu dalam pemakaiannya perlu dialokasikan memori yang dipakainya dengan perintah new.
3.2.1 Deklarasi Array
Suatu array dideklarasikan dengan cara
DataType
[]
VariableName
;
Contoh :
using System;
public class Exercise
{
static void Main()
{
double[] numbers;
}
}
3.2.2. Inisialisasi Array
Inisialisasi array dilakukan dengan perintah new. Formatnya adalah : VarableName = new DataType[angka];
Contoh
using System;
public class Exercise
{
static void Main()
{
double[] numbers;
// deklarasi
numbers = new double[5];
// inisialisasi
}
}
3.2.3. Assignment nilai pada array.
Array diisi dengan mengakses indexnya. Contoh :using System;
public class Exercise {
static void Main() {
double[] Numbers = new double[3]; Numbers[0] = 12.44;
Numbers[1] = 525.38; Numbers[2] = 6.28; }
Selain dengan menggunakan nilai indeks untuk mengisi nilai, array dapat diisi nilainya sewaktu dideklarasikan.
Contoh :
using System;
public class Exercise {
static void Main() {
double[] Numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
} }
3.2.4. Mengambil nilai dalam array.
Nilai dalam array dapat diambil dengan menggunakan nilai indeksnya. Contoh :
using System;
public class Exercise
{
static void Main() {
double[] Numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
Console.Write("Number: {0} ", Numbers[3]); Console.Read();
} }
Menggunakan perulangan for
Menggunakan for untuk mengambil nilai dalam array. Formatnya adalah : for(DataType Initializer; EndOfRange; Increment) Aksi
DataType biasanya berupa tipe integer, karena indeks dari array adalah bertipe integer. Initializer adalah nilai awal dari array yang akan diambil. EndOfRange merupakan nilai indeks terakhir yang akan diakses, biasanya menggunakan pembanding seperti <, <=, >, >=, =.
Contoh
using System;
public class Exercise
{
static void Main() {
double[] Numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
for (int i = 0; i < 5; i++)
Console.WriteLine(Numbers[i]); Console.Read();
} }
Hasil eksekusi: 12.44 525.38 6.28 2448.32 632.04
Menggunakan foreachSelain perulangan dengan perintah for, maka pada array dapat dilakukan perulangan dengan perintah foreach. Formatnya adalah
foreach (type identifier in expression) statement Contoh :
using System;
public class Exercise
{
static void Main() {
double[] Numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
foreach (double n in Numbers)
Console.WriteLine("Number: {0} ", n); Console.Read();
} }
3.2.5. Array Multi Dimensi
Array dua dimensi dideklarasikan dengan format sebagai berikut :
DataType[,,] VariableName = new DataType[Number1,Number2,Number3];
DataType adalah tipe data yang digunakan.
Number1, Number2, Number3 adalah jumlah dari elemen. Contoh
using System;
public static class Exercise {
public static void Main(string[] args) {
String[,] Members = new string[2, 4];
Console.Read(); }
}
Inisialisasi array multi dimensi
Inisialisasi array multi dimensi sama dengan cara menginisialisasi arrray satu dimensi.
Contoh
using System;
public static class Exercise
{
{
double[,] Prices = new double[5, 8] { { 10.50, 2.35, 49.75, 202.35, 8.70, 58.20, 34.85, 48.50 }, { 23.45, 878.50, 26.35, 475.90, 2783.45, 9.50, 85.85, 792.75}, { 47.95, 72.80, 34.95, 752.30, 49.85, 938.70, 45.05, 9.80 }, { 759.25, 73.45, 284.35, 70.95, 82.05, 34.85, 102.30, 84.50}, { 29.75, 953.45, 79.55, 273.45, 975.90, 224.75, 18.25, 34.05} }; Console.ReadKey(); return 0; } }
Cara pengaksesan nilai dalam array dapat dilakukuan dengan cara Mengakses secara langsung nilai indeksnya
Dengan menggunakan perulangan secara nested Contoh
using System;
public static class Exercise
{
static void Main(string[] args) {
double[,,] Number = new double[2, 2, 2]; Number[0, 0, 0] = 12.44; Number[0, 0, 1] = 525.38; Number[0, 1, 0] = -378.05; Number[0, 1, 1] = 48.14; Number[1, 0, 0] = 48.02; Number[1, 0, 1] = 120.44; Number[1, 1, 0] = 56.85; Number[1, 1, 1] = 105.48;
for (int Outside = 0; Outside < 2; Outside++) for (int Inside = 0; Inside < 2; Inside++) for (int Value = 0; Value < 2; Value++) Console.WriteLine("Number = {0}", Number[Outside, Inside, Value]); Console.ReadKey();
} }
Dengan menggunakan foreach Contoh
using System;
public static class Exercise
{
static void Main(string[] args) {
double[,,] Number = new double[2, 2, 2]; Number[0, 0, 0] = 12.44;
Number[0, 1, 0] = -378.05; Number[0, 1, 1] = 48.14; Number[1, 0, 0] = 48.02; Number[1, 0, 1] = 120.44; Number[1, 1, 0] = 56.85; Number[1, 1, 1] = 105.48;
foreach (double Value in Number)
Console.WriteLine("Number: {0}", Value); Console.ReadKey();
} }
3.3. String
Tipe String adalah tipe data yang merupakan rangkaian dari karakter. Untuk variabel yang hanya berisikan satu karakter sebaiknya menggunakan tipe data char. Contoh
using System;
public static class Exercise
{
public static void Main(string[] args) {
char Gender = 'm'; char MoneySymbol = '$'; char Multiplication = '*'; char NumberOne = '1';
Console.WriteLine("A few characters");
Console.WriteLine("Gender: {0}", Gender); Console.WriteLine("Money Symbol: {0}", MoneySymbol); Console.WriteLine("Multiplication: {0}", Multiplication); Console.WriteLine("Number One: {0}", NumberOne); Console.ReadKey();
} }
String adalah tipe data yang menampung serangkaian karakter, dapat juga dianggap sebagai array yang bertipe char.
Contoh:
using System; class Exercise
{
static void Main(string[] args) {
string gender = "Female";
Console.WriteLine("Gender: {0}", gender); Console.WriteLine("\nIndividual Characters"); foreach (char c in gender)
Console.WriteLine("Character: {0}", c); Console.ReadKey();
} }
3.3.1 Method dalam String
1.
ToUpper() mengubah Huruf menjadi HURUF BESAR.2.
ToLower() mengubah Huruf menjadi huruf kecil3.
Replace(char oldChar, char newChar) mengganti karakter oldChar yang ada dalam string menjadi karakter newChar.Contoh
using System;
public class Program
{
static void Main(string[] args) {
String PhoneNumber = "";
PhoneNumber = Console.ReadLine();
// Get a telephone number from the user
Console.WriteLine("\nPhone Number: " + PhoneNumber);
// Remove the spaces
PhoneNumber = PhoneNumber.Replace(" ", "");
Console.WriteLine("\nPhone Number: " + PhoneNumber);
// Remove the left parenthesis, if any
PhoneNumber = PhoneNumber.Replace("(", "");
// Remove the right parenthesis, if any
PhoneNumber = PhoneNumber.Replace(")", "");
// Remove the dash, if any
PhoneNumber = PhoneNumber.Replace("-", "");
Console.WriteLine("\nPhone Number: " + PhoneNumber +"\n");
Console.ReadKey(); }
}
4.
Length mendapatkan panjang dari suatu string. Contohusing System;
public class Exercise
{
static void Main(string[] args) {
String gender = "Female";
Console.WriteLine("Gender: {0}", gender); Console.WriteLine("Length: {0}
Characters",gender.Length);
Console.WriteLine("\nIndividual Characters"); for (int c = 0; c < gender.Length; c++)
Console.WriteLine("Index[{0}]: {1}", c, gender[c]); Console.ReadKey();
} }
5.
Replace(string oldStr, string newStr) mengganti sub String oldStr menjadi sub String newStr.6.
Format(string format, Object arg0) mengganti format String menjadi format yang lain.Contoh
using System;
public class Exercise
{
static void Main(string[] args) {
double wage = 22.45;
String strDsp = string.Format("Hourly Salary: {0}", wage); Console.WriteLine(strDsp);
Console.ReadKey(); }
}
Secara Langsung Contoh
using System;
public class Exercise
{
static void Main(string[] args) {
string strPerson = "Charles Stanley"; string strSomebody = strPerson;
Console.WriteLine("Full Name: " + strPerson); Console.WriteLine("Full Name: " + strSomebody); Console.ReadKey();
} }
Dengan Method Copy(string str)using System;
public class Exercise
{
static void Main(string[] args) {
string strPerson = "Charles Stanley";
string strSomebody = string.Copy(strPerson); Console.WriteLine("Full Name: " + strPerson); Console.WriteLine("Full Name: " + strSomebody); Console.ReadKey();
} }
8. CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
Contoh
using System;
public class Exercise
{
static void Main(string[] args) {
string strPerson = "Charles Stanley"; char[] charSomebody =new char[7];
strPerson.CopyTo(0, charSomebody, 0, 7); Console.WriteLine("Full Name: " + strPerson); for(int i= 0; i <strSomebody.Length; i++) Console.Write(charSomebody[i]);
Console.ReadKey(); }
9.
Concatenation penggabungan string Ada dua cara yaitu : Dengan menggunakan operator + Contoh
using System;
public class Exercise
{
static void Main(string[] args) {
string strNeed = "Needs"; string strRepair = "Repair";
string strAddition = strNeed + strRepair; Console.WriteLine(strAddition);
Console.ReadKey(); }
}
Dengan method Concat(string str0, string str1, string str2); Contohusing System;
public class Exercise
{
static void Main(string[] args) {
string strNeed = "Needs"; string strRepair = "Repair";
string strAddition = string.Concat(strNeed ,strRepair);
Console.WriteLine(strAddition); Console.ReadKey();
} }
10.
Compare(string String1, string String2) membandingkan dua string mengembalikan nilai 1 untuk String1 > String2, -1 untuk String1< String2 dan nilai 0 apabila kedua String bernilai samaContoh
using System;
public class Exercise
{
static void Main(string[] args) {
string FirstName1 = "Andy"; string LastName1 = "Stanley"; string FirstName2 = "Charles"; string LastName2 = "Stanley";
int Value1 = string.Compare(FirstName1,FirstName2); int Value2 = string.Compare(FirstName2, FirstName1); int Value3 = string.Compare(LastName1, LastName2);
Console.WriteLine("The result of comparing " +
FirstName1 + " and " + FirstName2 + " is\t" + Value1.ToString());
Console.WriteLine("The result of comparing " +
FirstName2 + " and " + FirstName1 + " is\t" + Value2.ToString());
Console.WriteLine("The result of comparing " + LastName1 + " and " + LastName2 + " is\t" + Value3.ToString() + "\n"); Console.ReadKey();
} }
Method ini memperhatikan juga huruf kecil dan huruf besar. Untuk mengabaikan adanya huruf kecil dan huruf besar digunakan
Compare(string String1, string String2, bool ignoreCase);
11.
Equals(string value) membandingkan apakah kedua string sama. Memberikan nilai kembalian berupa booleanContoh
using System;
public class Exercise
{
static void Main(string[] args) {
string FirstName1 = "Andy"; string LastName1 = "Stanley"; string FirstName2 = "Charles"; string LastName2 = "Stanley";
int Value1 = string.Compare(FirstName1,FirstName2); int Value2 = string.Compare(FirstName2, FirstName1); int Value3 = string.Compare(LastName1, LastName2); Console.WriteLine("The result of comparing " +
FirstName1 + " and " + FirstName2 + " is\t" + Value1.ToString());
Console.WriteLine("The result of comparing " +
FirstName2 + " and " + FirstName1 + " is\t" + Value2.ToString());
Console.WriteLine("The result of comparing " + LastName1 + " and " + LastName2 + " is\t" + Value3.ToString() + "\n"); if (LastName1.Equals(LastName2))
Console.WriteLine("Satu Keluarga"); Console.ReadKey();
} }