Metodlar ve Parametreler
Download
Report
Transcript Metodlar ve Parametreler
Metodlar ve Parametreler
menü
Java’da Program Moduleri
Math-Class Metodları
Method Tanıtımı
Argumanın Veri Tipi Yükseltmesi
Random-Sayı Üretmek
Erişim Alanları
JApplet Sınıfının Metodları
Method Overloading (Aşırı Yükleme )
Yineleme
Yineleme Problemlerine Örnek: The Fibonacci Series
Yineleme ve Döngüler
Giriş
• Modüller
– Problemi küçük parçalara ayırma
• e.g., böl ve fethet
– Büyük ve kompleks problemlerin dizaynını, implementation
ve bakımını kolaylaştırır.
– Implementation= gerçekleştirme ,yerine getirme ,hayata
geçirme
Java’da Program Modülleri
• Java’da Modüller
– Methodlar
– Sınıflar (Classlar)
• Java API birçok modül sağlar.
• Programcılarda aynı zamanda kendileri modüller
oluşturabilirler.
– e.g., kullanıcı tanımlı metodlar
• Metodlar
– Metod çağrıcı tarafından uyarılır.
– Metod çağırana bir değer dönderir.
– Bir yöneticinin bir personeline işini bitirip bitirmediğini
sorması gibi.
yönet
ici
işçi1
işçi4
işçi2
işçi3
işçi5
Yönetici-metod / işçi metod arasındaki hiyerarşik ilişki.
Math-Sınıfı Methodları
• Class java.lang.Math
– Çok kullanılan matematik hesaplamaları sağlar
– 900.0 sayısının kare kökünü al:
• Math.sqrt( 900.0 )
– Method sqrt class Math sınıfına ait
• Nokta (.) sqrt methoduna erişimi sağlıyor.
– Argument 900.0 ise parantez içine yazılır.
M ethod
abs( x )
D escription
absolute value of x (this m ethod also has float, int and long versions)
ceil( x )
rounds x to the sm allest integer not less than x
cos( x )
exp( x )
trigonom etric cosine of x (x is in radians)
exponential m ethod ex
floor( x )
rounds x to the largest integer not greater than x
log( x )
natural logarithm of x (base e)
max( x, y )
pow( x, y )
larger value of x and y (this m ethod also has float, int and long
versions)
sm aller value of x and y (this m ethod also has float, int and long
versions)
x raised to the pow er y (xy)
sin( x )
sqrt( x )
trigonom etric sine of x (x is in radians)
square root of x
tan( x )
trigonom etric tangent of x (x is in radians)
min( x, y )
Fig. 6.2 Math -class m ethods.
E xam ple
abs( 23.7 ) is 23.7
abs( 0.0 ) is 0.0
abs( -23.7 ) is 23.7
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( 0.0 ) is 1.0
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
log( Math. E ) is 1.0
log( Math. E * Math.E ) is 2.0
max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
min( 2.3, 12.7 ) is 2.3
min( -2.3, -12.7 ) is -12.7
pow( 2.0, 7.0 ) is 128.0
pow( 9.0, 0.5 ) is 3.0
sin( 0.0 ) is 0.0
sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( 0.0 ) is 0.0
Metodların Tanıtımı
• Metodlar
– Programcıya modülleştirilmiş program yazma imkanını
sağlar.
• Programın yönetimini artırır.
• Yazılımların yeniden kullanabilirliği sağlar.
• Kodların tekrarlanmasını engeller.
– Lokal değişkenler
• Metod içinde tanıtılırlar.
– global değişkenler
• Metod dışında,classiçinde tanıtılırlar.
– Parametreler
• Metod ile metodu çağıran arasında bilgi alışverişini sağlarlar.
•Programcı kendi metodlarını yazabilir.
import java.applet.*;
import java.awt.*;
public class kareAlma extends Applet {
public void paint(Graphics g){
int y=20;
int sonuc=0;
for ( int sayac = 1; sayac <= 10; sayac++ )
{
sonuc = karesi( sayac ); // method çağırma
g.drawString (""+sayac+" karesi ="+sonuc,30,y+=20);
} // end for
}// paint
public int karesi( int sayi )
{
return sayi * sayi;
} // end karesi
}
// return square of y
Method Tanıtımı
• Metod tanıtımının genel formatı:
geri-dönüş-tipi metod-ismi( parametre1, parametre2, …, parametreN )
{
değişken tanıtımı ve kod bloğu
}
• Metod ayrıca return değerleri de olabilir:
return değer;
// Üçgen çizdirme programı
import java.awt.*;
import java.applet.Applet;
public class ucgenCiz extends Applet {
public void paint(Graphics g) {
int tabanX=80;
int tabanY=200;
int taban=100;
int height=110;
g.drawLine(tabanX, tabanY, tabanX+ taban, tabanY);
g.drawLine(tabanX+ taban, tabanY, tabanX+ taban/2, tabanYheight);
g.drawLine(tabanX+ taban/2, tabanY-height, tabanX, tabanY);
}
}
// Üçgen çizdirme metodu
import java.awt.*;
import java.applet.Applet;
public class x extends Applet {
public void paint(Graphics g) {
drawTriangle(g,20,180,100,110);
drawTriangle(g,125,180,60,70);
}
private void drawTriangle(Graphics g,int tabanX, int tabanY,
int taban,int yukseklik) {
int sagX = tabanX+taban;
int ustX = tabanX+taban/2;
int ustY = tabanY-yukseklik;
g.drawLine(tabanX,tabanY, sagX,tabanY);
g.drawLine(sagX,tabanY,ustX,ustY);
g.drawLine(ustX,ustY, tabanX,tabanY);
}
}
Method Tanıtımı
• Metod geri değer döndermiyorsa;
– Metod tanıtımı
private void methodIsmi (veri-tipi parametre-listesi){
gövde
}
– Metod çağırımı
methodIsmi (parametre-listesi)
• Metod geri değer dönderiyorsa
– Metod tanıtımı
private int methodIsmi (veri-tipi parametre-listesi){
gövde
return değer;
}
– Metod çağırımı
int n=methodIsmi ( parametre-listesi)
• Metodun parametresi yok ise;
private void methodIsmi (){
gövde
}
// Ev çizimi
import java.awt.*;
import java.applet.Applet;
public class x extends Applet
{
public void paint(Graphics g) {
evCiz(g,50,50, 70,30);
evCiz(g,100,50,60,20);
}
private void ucgenCiz(Graphics g,int tabanX, int tabanY,
int taban,int yukseklik) {
g.drawLine(tabanX,tabanY, tabanX+taban,tabanY);
g.drawLine(tabanX+taban,tabanY,tabanX+taban/2,tabanYyukseklik);
g.drawLine(tabanX+taban/2,tabanY-yukseklik, tabanX,tabanY);
}
private void evCiz(Graphics g,int tabanX,int tabanY,
int width,int yukseklik) {
g.drawRect(tabanX, tabanY-yukseklik, width,yukseklik);
ucgenCiz(g,tabanX, tabanY-yukseklik,width, yukseklik/2);
}
}
14
Method Tanıtımı
• Örnek: sayılar parametre olarak gönderilecek
• İki integer sayıyı toplayan bir metod yazınız
• İki double sayıyı toplayan ve sonucu dönderen bir metod
yazınız.
• İki sayıdan büyük olanını dönderen bir metod yazınız
• üç sayıdan küçük olanını dönderen bir metod yazınız
• santigratı Kelvine çeviren metod yazınız
K=273+C
• Gaz basıncını hesaplayan metodu yazınınız(v,n,t parametre olacak)
P.V=N.R.T
n:mol miktarı, t: kelvin cinsinden sıcaklık,r:gaz sabiti( 22,4 / 273 ),
v:hacim, p:basınç
örnek:Bir ideal gazın 1.5 molü kapalı bir kap içinde 27.8 L
hacimdedir.12°C'de gazın basıncı nedir?
2003 Prentice Hall, Inc. All rights reserved.
1
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// MaximumTest.java // ondalılı 3 sayının en büyüğü.
import java.awt.Container;
import javax.swing.*;
public class MaximumTest extends JApplet {
// initialize applet by obtaining user input and creating GUI
public void init()
{
// obtain user input
String s1 = JOptionPane.showInputDialog(
“1.sayıyı giriniz(ondalıklı)" );
String s2 = JOptionPane.showInputDialog(
" 2.sayıyı giriniz(ondalıklı) " );
String s3 = JOptionPane.showInputDialog(
" 3.sayıyı giriniz(ondalıklı) " );
// convert user input to double values
double number1 = Double.parseDouble( s1 );
double number2 = Double.parseDouble( s2 );
double number3 = Double.parseDouble( s3 );
double max = maximum( number1, number2, number3 ); // method call
double min = manimum( number1, number2, number3 ); // method call
// create JTextArea to display results
JTextArea outputArea = new JTextArea();
// display numbers and maximum value
outputArea.setText( "number1: " + number1 + "\nnumber2: " +
number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );
// yazı alanını göstermek için applet kullanıcı arayüzü bileşenlerini kullan
35
36
37
38
39
40
41
45
46
47
48
42
44
45
46
47
48
49
50
Container c = getContentPane();
//container: kap,yüklenici anlamında
// Container c ye outputAraea nesnensini ekle
c.add( outputArea );
} // end method init
public double minumum( double x, double y, double z )
{
return Math.min( x, Math.min( y, z ) );
} // en metod min
public double maximum( double x, double y, double z )
{
return Math.max( x, Math.max( y, z ) );
} // end method maximum
} // end class Maximum
Random-Sayı Üretme
• Java random-sayı üreticisi
– Math.random()
• ( int ) ( Math.random() * 6 )
– 0 ile 5 arası integer sayı üretir.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// RandomIntegers.java
// Shifted, scaled random integers.
import javax.swing.JOptionPane;
public class RandomIntegers {
public static void main( String args[] )
{
int value;
String output = "";
// loop 20 times
for ( int counter = 1; counter <= 20; counter++ ) {
// 1 ve 6 arasında rastgele integer sayı
value = 1 + ( int ) ( Math.random() * 6 );
output += value + "
";
// append value to output
// if counter divisible by 5, append newline to String output
if ( counter % 5 == 0 )
output += "\n";
} // end for
26
27
28
29
30
31
32
33
34
JOptionPane.showMessageDialog( null, output,
"20 Random Numbers from 1 to 6",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class RandomIntegers
JApplet Sınıfının Metodları
• Java API birçok JApplet metodları
tanımlamıştır.
– Bu metodları yeniden JApplet te tanıtmaya overriding
(eskisini geçersiz kılma) denir.
Metod
Açıklama
public void init ()
Applet yüklenirken bir defa çağrılır.Appletin yüklenirken ilk
değerleri almasını gerçekleştirir.Bu metodda yapılan işler ;
değişkenlere ilk değer verme, GUI araçlarını oluşturma, ses
dosyalarını yükleme, resimleri yükleme
public void start ()
init() metodu bittikten sonra çağrılır veya kullanıcı başka bir web
sayfasına geçiş yapıp tekrar appletli web sayfasına döndüğünde
start() metodu tekrar çağrılır. Bu metodda yapılan işler; animasyon
veya thread başlatmak
public void paint
(Graphics g)
init() metodu bitiminde, start() metodu başlangıcında çizim metodu
çağrılır.Appletin yeniden çizimine ihtiyaç olduğu heran bu metod
çağrılır.
public void stop ()
Kullanıcı appletli web sayfasını terk ettiğinde çalışan herşey askıya
alınır.Animasyon yada threadlerin durması gibi...
public void destroy ()
Appletin bellekten silineceği zaman çağrılır.Kullanıcı sayfayı
kapattığında olduğu gibi...
Method Overloading (Aşırı Yükleme)
• Method overloading
– Aynı isimli birden fazla metod olabilir.
– Her metod için ayrı parametreler set edilir.
• Parametre sayısı
• Parametre tipi
1 // MethodOverload.java // overloaded (aşırı yüklenmiş) metodlar kullanma
2
import java.awt.Container;
4
import javax.swing.*;
6
7
public class MethodOverload extends JApplet {
8
// create GUI and call each square method
10
public void init()
11
{
12
JTextArea outputArea = new JTextArea();
13
Container container = getContentPane();
14
container.add( outputArea );
15
16
outputArea.setText( “integer 7 nin karesi " + karesi( 7 ) +
17
"\r double 7.5 in karesi " + karesi( 7.5 ) );
18
19
} // end method init
20
21
// square method with int argument
22
public int karesi( int intValue )
23
{
24
System.out.println( “karesi metodu int “+ intValue +” ile çağrıldı ");
26
return intValue * intValue;
29
} // end
30
// square method with double argument
32
public double karesi( double doubleValue )
33
{
34
System.out.println( “karesi metodu double “+ doubleValue +” ile çağrıldı ");
37
return doubleValue * doubleValue;
38
39
} // end method square with double argument
40
} // end class
Karesi metodu int 7 ile çağrıldı
Karesi metodu double 7.5 ile çağrıldı
import java.awt.Graphics;
import javax.swing.JApplet;
public class asiriYukleme extends JApplet{
public void paint(Graphics g){
super.paint(g);
g.drawString("int 2 nin karesi: "+karesi(2),0,25);
g.drawString("double 5.5 in karesi "+karesi(5.5),0,45);
}
public int karesi( int x )
{
return x * x;
}
public double karesi( int x )
{
return x * x;
MethodOverload.java:15:
square(int) is already defined in MethodOverload
public double square( int y )
}
^
} 1 error
java.lang.Error: Unresolved compilation problems:
The method karesi(int) is undefined for the type asiriYukleme
The method karesi(double) is undefined for the type asiriYukleme
Duplicate method karesi(int) in type asiriYukleme
Duplicate method karesi(int) in type asiriYukleme
Recursion (Yineleme)
• Yineleme metodu
– Başka metoddan kendisini çağırması
– Metod sadece ilk değer sonucunu bilir.
– Method problemi 2’ye ayırır
• İlk kısım
• Basit problemler
• Problem çözülene dek problemi küçük parçalara ayırıp
sonucunu bulur.
– Yineleyerek çağırma
– Yineleme basamakları
Final value = 120
5!
5!
5! = 5 * 24 = 120 is returned
5 * 4!
5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3!
4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2!
3 * 2!
2! = 2 * 1 = 2 is returned
2 * 1!
2 * 1!
1 returned
1
1
(a) Sequence of recursive calls.
(b) Values returned from each recursive call.
Fig. 6.14 Recursive evaluation of 5!.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
22
23
25
26
27
28
29
30
32
33
34
35
36
37
38
// Fig. 6.15: FactorialTest.java
// Recursive factorial method.
import java.awt.*;
import javax.swing.*;
public class FactorialTest extends JApplet {
JTextArea outputArea;
// create GUI and calculate factorials of 0-10
public void init()
{
outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
// calculate the factorials of 0 through 10
for ( long counter = 0; counter <= 10; counter++ )
outputArea.append( counter + "! = " +factorial( counter ) + "\n" );
} // end method init
// recursive declaration of method factorial
public long factorial( long number )
{
// base case
if ( number <= 1 )
return 1;
// recursive step
else
return number * factorial( number - 1 );
} // end method factorial
} // end class FactorialTest
Yineleme Problemlerine Örnek The
Fibonacci Series
• Fibonacci series
– Serideki her numara kendinden önceki 2 tanenin toplamıdır
• e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21…
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 2 )
• fibonacci(0) and fibonacci(1) are base cases
– Golden ratio (golden mean)
1
3
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
);
21
22
23
24
25
26
27
28
// Fig. 6.16: FibonacciTest.java
// Recursive fibonacci method.
import java.awt.*;
import java.awt.event.*; // enter eventi
import javax.swing.*;
public class FibonacciTest extends JApplet implements ActionListener {
JLabel numberLabel, resultLabel;
JTextField numberField, resultField;
// set up applet’s GUI
public void init()
{
// content pane tanmla ve layout(yerleşim) olarak FlowLayout set et
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// label tanımla ve konteynıra ekle
numberLabel = new JLabel( “integer sayı giriniz ve enter a basınız"
container.add( numberLabel );
// sayı girilebilecek text alanı tanımla ve konteynıra ekle
numberField = new JTextField( 10 );
container.add( numberField );
// numberField ın ActionListener ( hareket listesini) bu aplete ekle
numberField.addActionListener( this );
30
31
32
33
34
35
37
38
39
40
41
42
43
44
45
46
49
50
51
52
53
54
55
56
57
58
59
// sonuc labelı oluştur ve conteynıra ekle
resultLabel = new JLabel( "Fibonacci değeri" );
container.add( resultLabel );
// text alanı oluştur, ve edit edilmesini engelle ve konteynıra ekle
resultField = new JTextField( 15 );
resultField.setEditable( false );
container.add( resultField );
} // end method init
// kullanıcı entera basınca bu metod tetkilencek
public void actionPerformed( ActionEvent event )
{
long number, fibonacciValue;
number = Long.parseLong( numberField.getText() );
//işlem devam ediyor, statusbar( durum çubuğunda)
showStatus( “hesaplanıyor ..." );
// girilen sayı için fibonacci değerini hesapla
fibonacciValue = fibonacci( number );
// işlemin tamamnladığını göster
showStatus( “tamamlandı." );
resultField.setText( Long.toString( fibonacciValue ) );
} // end method actionPerformed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// fibonacci metodu recursif(kendini açğıran ) olarak tanımla
public long fibonacci( long n )
{
// base case
if ( n == 0 || n == 1 )
return n;
// recursive step
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
} // end method fibonacci
} // end class FibonacciTest
fibonacci( 3 )
return
return
fibonacci( 1 )
return 1
fibonacci( 2 )
+
+
fibonacci( 1 )
fibonacci( 0 )
return 0
Fig. 6.17 Set of recursive calls for fibonacci (3).
return 1