bölüm 6 – metod lar ve parametreler

51
Bölüm 6 – Metodlar ve Parametreler İçindekiler 6.1 Giriş 6.2 Java’da Program Moduleri 6.3 Math-Class Metodları 6.4 Method Tanıtımı 6.5 Argumanın Veri Tipi Yükseltmesi 6.7 Random-Sayı Üretmek 6.9 Erişim Alanları 6.10 JApplet Sınıfının Metodları 6.11 Method Overloading (Aşırı Yükleme ) 6.12 Yineleme 6.13 Yineleme Problemlerine Örnek: The Fibonacci Series 6.14 Yineleme ve Döngüler

Upload: leoma

Post on 11-Feb-2016

49 views

Category:

Documents


0 download

DESCRIPTION

Bölüm 6 – Metod lar ve Parametreler. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Bölüm  6 – Metod lar ve Parametreler

Bölüm 6 – Metodlar ve Parametrelerİçindekiler6.1 Giriş6.2 Java’da Program Moduleri6.3 Math-Class Metodları6.4 Method Tanıtımı 6.5 Argumanın Veri Tipi Yükseltmesi 6.7 Random-Sayı Üretmek6.9 Erişim Alanları 6.10 JApplet Sınıfının Metodları 6.11 Method Overloading (Aşırı Yükleme )6.12 Yineleme 6.13 Yineleme Problemlerine Örnek: The Fibonacci Series 6.14 Yineleme ve Döngüler

Page 2: Bölüm  6 – Metod lar ve Parametreler

6.1 Giriş

• Modüller– Problemi küçük parçalara ayırma

• e.g., böl ve fethet – Büyük ve kompleks problemlerin dizaynını,

implementasyonunu ve bakımını kolaylaştırır.

Page 3: Bölüm  6 – Metod lar ve Parametreler

6.2 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.

Page 4: Bölüm  6 – Metod lar ve Parametreler

Fig. 6.1 Yönetici-metod / işçi metod arasındaki hiyerarşik ilişki.

yönetici

işçi1 işçi2 işçi3

işçi4 işçi5

Page 5: Bölüm  6 – Metod lar ve Parametreler

6.3 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.

Page 6: Bölüm  6 – Metod lar ve Parametreler

Method Description Example abs( x ) absolute value of x (this method also has float, int and long versions) abs( 23.7 ) is 23.7

abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7

ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0 exp( x ) exponential method ex exp( 1.0 ) is 2.71828

exp( 2.0 ) is 7.38906 floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0

floor( -9.8 ) is -10.0 log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0

log( Math.E * Math.E ) is 2.0 max( x, y ) larger value of x and y (this method also has float, int and long

versions) max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3

min( x, y ) smaller value of x and y (this method also has float, int and long versions)

min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to the power y (xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0

sin( x ) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0 sqrt( x ) square root of x sqrt( 900.0 ) is 30.0

sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0 Fig. 6.2 Math-class methods.

Page 7: Bölüm  6 – Metod lar ve Parametreler

6.4 Metodların Tanıtımı

• Metodlar– Programcıya modülerize olmuş 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.

– Parametreler• Metod ile metodu çağıran arasında bilgi alışverişini sağlarlar.

Page 8: Bölüm  6 – Metod lar ve Parametreler

6.4 Metodların Tanıtımı

• Programcı kendi metodlarını yazabilir.

Page 9: Bölüm  6 – Metod lar ve Parametreler

import java.applet.*;import java.awt.*; public class Max extends Applet { public void paint(Graphics g){ int y=20; int sonuc=0; for ( int sayac = 1; sayac <= 10; sayac++ ) { sonuc = karesi( sayac ); // method call g.drawString (""+sayac+" karesi ="+sonuc,30,y+=20); } // end for }

public int karesi( int sayi ) { return sayi * sayi; // return square of y } // end method }

Page 10: Bölüm  6 – Metod lar ve Parametreler

6.4 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;

Page 11: Bölüm  6 – Metod lar ve Parametreler

// Üçgen çizdirme programıimport java.awt.*;import java.applet.Applet;public class TriangleTry extends Applet { public void paint(Graphics g) { int bottomX=80; int bottomY=200; int base=100; int height=110;

g.drawLine(bottomX,bottomY, bottomX+base,bottomY); g.drawLine(bottomX+base,bottomY,bottomX+base/2,bottomY-height); g.drawLine(bottomX+base/2,bottomY-height, bottomX,bottomY);

}}

Page 12: Bölüm  6 – Metod lar ve Parametreler

// Üçgen çizdirme metoduimport java.awt.*;import java.applet.Applet;

public class TriangleMethodDemo extends Applet {

public void paint(Graphics g) { drawTriangle(g,80,200,100,110); drawTriangle(g,125,220,60,70); } private void drawTriangle(Graphics g,int bottomX, int bottomY, int base,int height) { int rightX = bottomX+base; int topX = bottomX+base/2; int topY = bottomY-height;

g.drawLine(bottomX,bottomY, rightX,bottomY); g.drawLine(rightX,bottomY,topX,topY); g.drawLine(topX,topY, bottomX,bottomY); } }

Page 13: Bölüm  6 – Metod lar ve Parametreler

6.4 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}

Page 14: Bölüm  6 – Metod lar ve Parametreler

// Ev çizimi

import java.awt.*;import java.applet.Applet;public class HouseDemo extends Applet{ public void paint(Graphics g) { drawHouse(g,50,50, 70,30); drawHouse(g,100,50,60,20); }

private void drawTriangle(Graphics g,int bottomX, int bottomY, int base,int height) { g.drawLine(bottomX,bottomY, bottomX+base,bottomY); g.drawLine(bottomX+base,bottomY,bottomX+base/2,bottomY-height); g.drawLine(bottomX+base/2,bottomY-height, bottomX,bottomY); }

private void drawHouse(Graphics g,int bottomX,int bottomY, int width,int height) { g.drawRect(bottomX, bottomY-height, width,height); drawTriangle(g,bottomX, bottomY-height,width, height/2); }}

Page 15: Bölüm  6 – Metod lar ve Parametreler

Maximum.java

Lines 13-18User inputs three Strings

Lines 21-23Convert Strings to doubles

Line 25Method init passes doubles as arguments to method maximum

1 // Fig. 6.4: MaximumTest.java2 // Finding the maximum of three floating-point numbers.3 import java.awt.Container;4 5 import javax.swing.*;6 7 public class MaximumTest extends JApplet {8 9 // initialize applet by obtaining user input and creating GUI10 public void init()11 {12 // obtain user input13 String s1 = JOptionPane.showInputDialog(14 "Enter first floating-point value" );15 String s2 = JOptionPane.showInputDialog(16 "Enter second floating-point value" );17 String s3 = JOptionPane.showInputDialog(18 "Enter third floating-point value" );19 20 // convert user input to double values21 double number1 = Double.parseDouble( s1 );22 double number2 = Double.parseDouble( s2 );23 double number3 = Double.parseDouble( s3 );24 25 double max = maximum( number1, number2, number3 ); // method call26 27 // create JTextArea to display results28 JTextArea outputArea = new JTextArea();29 30 // display numbers and maximum value 31 outputArea.setText( "number1: " + number1 + "\nnumber2: " + 32 number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );33

User inputs three Strings

Convert Strings to doubles

Method init passes doubles as arguments to

method maximum

Page 16: Bölüm  6 – Metod lar ve Parametreler

Maximum.java

Line 46Method maximum returns value from method max of class Math

34 // get applet's GUI component display area35 Container container = getContentPane();36 37 // attach outputArea to Container c38 container.add( outputArea );39 40 } // end method init41 42 // maximum method uses Math class method max to help 43 // determine maximum value 44 public double maximum( double x, double y, double z )45 { 46 return Math.max( x, Math.max( y, z ) ); 47 48 } // end method maximum 49 50 } // end class Maximum

Method maximum returns value from method max of class Math

Page 17: Bölüm  6 – Metod lar ve Parametreler

6.5 Argumanın Veri Tipi Yükseltmesi

• Argumanlarda zorlama– Argumanlar metodlarda geçerken veri tipleri aynı olması

gerekir.

• e.g., System.out.println( Math.sqrt( 4 ) );

– Önce “ Math.sqrt( 4 )” hesaplanır

– Sonra “ System.out.println()” hesaplanır.

• Veri tipi yükseltme kuralları– Veri değeri kaybolmadan, nasıl tiplerin yükseltileceğinden

bahsedeceğiz.

Page 18: Bölüm  6 – Metod lar ve Parametreler

Veri Tipi Dönüşümü

• 2 tür tip dönüşümü vardır– Otomatik tip dönüşümü– Daraltma yaparak tip dönüşü (cast)

• Otomatik tip dönüşümü– Genişletici bir dönüşüm

Type Valid promotions double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double byte short, int, long, float or double boolean None (boolean values are not considered to be

numbers in Java) Fig. 6.5 Allowed promotions for primitive types.

Page 19: Bölüm  6 – Metod lar ve Parametreler

Veri Tipi Dönüşümü

• Daraltma yaparak tip dönüşü (cast)– Varolan veriyi daraltarak başka uyumlu bir veri tipine

sığdırma– (hedef-tip) değer

Page 20: Bölüm  6 – Metod lar ve Parametreler

Örnek 1 int a;byte b;// ...b = (byte) a;

Örnek 2// Demonstrate casts.class Conversion { public static void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); }}

Page 21: Bölüm  6 – Metod lar ve Parametreler

İfadelerde Otomatik Tip YükseltilmesiÖrnek 3byte a = 40;byte b = 50;byte c = 100;int d = a * b / c;

Örnek 4byte b = 50;b = b * 2; // Error! Cannot assign an int to a byte!

Örnek 5byte b = 50;b = (byte)(b * 2);

listing 21class Promote { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); }}

Page 22: Bölüm  6 – Metod lar ve Parametreler

6.7 Random-Sayı Üretme

• Java random-sayı üreticisi– Math.random()

• ( int ) ( Math.random() * 6 )

– 0 ile 5 arası integer sayı üretir.

Page 23: Bölüm  6 – Metod lar ve Parametreler

RandomIntegers.java

Line 16Produce integers in range 1-6

Line 16Math.random returns doubles. We cast the double as an int

1 // Fig. 6.7: RandomIntegers.java2 // Shifted, scaled random integers.3 import javax.swing.JOptionPane;4 5 public class RandomIntegers {6 7 public static void main( String args[] )8 {9 int value;10 String output = "";11 12 // loop 20 times13 for ( int counter = 1; counter <= 20; counter++ ) {14 15 // pick random integer between 1 and 6 16 value = 1 + ( int ) ( Math.random() * 6 );17 18 output += value + " "; // append value to output19 20 // if counter divisible by 5, append newline to String output21 if ( counter % 5 == 0 )22 output += "\n";23 24 } // end for25

Produce integers in range 1-6

Math.random returns doubles. We cast the double as an int

Page 24: Bölüm  6 – Metod lar ve Parametreler

RandomIntegers.java

26 JOptionPane.showMessageDialog( null, output, 27 "20 Random Numbers from 1 to 6", 28 JOptionPane.INFORMATION_MESSAGE );29 30 System.exit( 0 ); // terminate application31 32 } // end main33 34 } // end class RandomIntegers

Page 25: Bölüm  6 – Metod lar ve Parametreler

RollDie.java

Line 14Produce integers in range 1-6

Lines 17-43Increment appropriate frequency counter, depending on randomly generated number

1 // Fig. 6.8: RollDie.java2 // Roll a six-sided die 6000 times.3 import javax.swing.*;4 5 public class RollDie {6 7 public static void main( String args[] )8 {9 int frequency1 = 0, frequency2 = 0, frequency3 = 0,10 frequency4 = 0, frequency5 = 0, frequency6 = 0, face;11 12 // summarize results13 for ( int roll = 1; roll <= 6000; roll++ ) {14 face = 1 + ( int ) ( Math.random() * 6 );15 16 // determine roll value and increment appropriate counter17 switch ( face ) {18 19 case 1:20 ++frequency1;21 break; 22 23 case 2:24 ++frequency2;25 break;26 27 case 3:28 ++frequency3;29 break;30

Produce integers in range 1-6

Increment appropriate frequency counter, depending on randomly generated number

Page 26: Bölüm  6 – Metod lar ve Parametreler

RollDie.java

31 case 4:32 ++frequency4;33 break;34 35 case 5:36 ++frequency5;37 break;38 39 case 6:40 ++frequency6;41 break;42 43 } // end switch44 45 } // end for46 47 JTextArea outputArea = new JTextArea();48 49 outputArea.setText( "Face\tFrequency" + "\n1\t" + frequency1 + 50 "\n2\t" + frequency2 + "\n3\t" + frequency3 + 51 "\n4\t" + frequency4 + "\n5\t" + frequency5 + 52 "\n6\t" + frequency6 );53 54 JOptionPane.showMessageDialog( null, outputArea,55 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE );56 57 System.exit( 0 ); // terminate application58 59 } // end main60 61 } // end class RollDie

Page 27: Bölüm  6 – Metod lar ve Parametreler
Page 28: Bölüm  6 – Metod lar ve Parametreler

6.9 Erişim Alanları

• Alan– Basit alan kuralları

• Bir parametre alanı• lokal-değişken alanı• Etiketli break veya continue ifadelerinde etiketin alanı• for deyiminde başlarken tanımlı değişkenlerin alanı • Bir sınıfın değişkeni yada metodunun alanı

Page 29: Bölüm  6 – Metod lar ve Parametreler

6.9 Erişim Alanları// Demonstrate block scope.class Scope { public static void main(String args[]) { int x; // known to all code within main

x = 10; if(x == 10) { // start new scope int y = 20; // known only to this block

// x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } // y = 100; // Error! y not known here

// x is still known here. System.out.println("x is " + x); }}

Page 30: Bölüm  6 – Metod lar ve Parametreler

Scoping.java

Line 11field x

Line 26Local variable x

Line 28Method start uses local variable x

1 // Fig. 6.10: Scoping.java2 // A scoping example.3 import java.awt.Container;4 5 import javax.swing.*;6 7 public class Scoping extends JApplet {8 JTextArea outputArea;9 10 // x bu sınıfın tüm metodlarından ulaşılabilir.11 int x = 1; 12 13 // create applet's GUI14 public void init()15 {16 outputArea = new JTextArea();17 Container container = getContentPane(); 18 container.add( outputArea );19 20 } // end method init21 22 // start metodu init metodu bitişinde çağrılır.23 24 public void start()25 {26 int x = 5; // start metodunun local değişkeni27 28 outputArea.append( "local x in start is " + x );29

Field x has class scope

Local variable x has block scope

Method start uses local variable x

Page 31: Bölüm  6 – Metod lar ve Parametreler

Scoping.java

Line 42Recreate variable x and initialize it to 25

Lines 40-50Method useLocal uses local variable x

30 useLocal(); // useLocal has local x31 useField(); // useInstance uses Scoping's field x32 useLocal(); // useLocal reinitializes local x33 useField(); // Scoping's field x retains its value34 35 outputArea.append( "\n\nlocal x in start is " + x );36 37 } // end method start38 39 // useLocal creates and initializes local variable x during each call40 public void useLocal()41 {42 int x = 25; // initialized each time useLocal is called43 44 outputArea.append( "\n\nlocal x in useLocal is " + x +45 " after entering useLocal" );46 ++x;47 outputArea.append( "\nlocal x in useLocal is " + x +48 " before exiting useLocal" );49 50 } // end method useLocal51

Re-create variable x and initialize it to 25

Method useLocal uses local variable x

Page 32: Bölüm  6 – Metod lar ve Parametreler

Scoping.java

Lines 53-61Method useField uses field x

52 // useField modifies Scoping's field x during each call53 public void useField()54 {55 outputArea.append( "\n\nfield x is " + x +56 " on entering useField" );57 x *= 10;58 outputArea.append( "\nfield x is " + x +59 " on exiting useField" );60 61 } // end method useInstance62 63 } // end class Scoping

Method useField uses field x

Page 33: Bölüm  6 – Metod lar ve Parametreler

6.16 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.

Page 34: Bölüm  6 – Metod lar ve Parametreler

Metod Açıklamapublic 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...

Page 35: Bölüm  6 – Metod lar ve Parametreler

6.15 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

Page 36: Bölüm  6 – Metod lar ve Parametreler

MethodOverload.java

Lines 22-29Method square receives an int as an argument

1 // Fig. 6.12: MethodOverload.java2 // Using overloaded methods3 import java.awt.Container;4 5 import javax.swing.*;6 7 public class MethodOverload extends JApplet {8 9 // create GUI and call each square method10 public void init()11 {12 JTextArea outputArea = new JTextArea();13 Container container = getContentPane();14 container.add( outputArea );15 16 outputArea.setText( "The square of integer 7 is " + square( 7 ) +17 "\nThe square of double 7.5 is " + square( 7.5 ) );18 19 } // end method init20 21 // square method with int argument 22 public int square( int intValue ) 23 { 24 System.out.println( "Called square with int argument: " +25 intValue ); 26 27 return intValue * intValue; 28 29 } // end method square with int argument 30

Method square receives an int as an argument

Page 37: Bölüm  6 – Metod lar ve Parametreler

MethodOverload.java

Lines 32-39Overloaded method square receives a double as an argument

31 // square method with double argument 32 public double square( double doubleValue ) 33 { 34 System.out.println( "Called square with double argument: " +35 doubleValue ); 36 37 return doubleValue * doubleValue; 38 39 } // end method square with double argument 40 41 } // end class MethodOverload

Called square with int argument: 7Called square with double argument: 7.5

Overloaded method square receives a double as an argument

Page 38: Bölüm  6 – Metod lar ve Parametreler

MethodOverload.java

Lines 8 and 15Compiler cannot distinguish between methods with identical names and parameter sets

Fig. 6.17 Compiler error messages generated from overloaded methods with identical parameter lists and different return types.

1 // Fig. 6.13: MethodOverload.java2 // Overloaded methods with identical signatures.3 import javax.swing.JApplet;4 5 public class MethodOverload extends JApplet {6 7 // declaration of method square with int argument8 public int square( int x )9 {10 return x * x;11 }12 13 // second declaration of method square 14 // with int argument causes syntax error15 public double square( int y ) 16 { 17 return y * y; 18 } 19 20 } // end class MethodOverload

MethodOverload.java:15: square(int) is already defined in MethodOverload public double square( int y ) ^1 error

Compiler cannot distinguish between methods with identical names and

parameter sets

Page 39: Bölüm  6 – Metod lar ve Parametreler

6.12 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ı

Page 40: Bölüm  6 – Metod lar ve Parametreler

Fig. 6.14 Recursive evaluation of 5!.

2! = 2 * 1 = 2 is returned

(a) Sequence of recursive calls. (b) Values returned from each recursive call.

Final value = 120

5! = 5 * 24 = 120 is returned

4! = 4 * 6 = 24 is returned

3! = 3 * 2 = 6 is returned

1 returned

5!

1

4 * 3!

3 * 2!

2 * 1!

5!

1

4 * 3!

3 * 2!

2 * 1!

5 * 4! 5 * 4!

Page 41: Bölüm  6 – Metod lar ve Parametreler

FactorialTest.java

Line 21Invoke method factorial

1 // Fig. 6.15: FactorialTest.java2 // Recursive factorial method.3 import java.awt.*;4 5 import javax.swing.*;6 7 public class FactorialTest extends JApplet {8 JTextArea outputArea;9 10 // create GUI and calculate factorials of 0-1011 public void init()12 {13 outputArea = new JTextArea();14 15 Container container = getContentPane();16 container.add( outputArea );17 18 // calculate the factorials of 0 through 1019 for ( long counter = 0; counter <= 10; counter++ )20 outputArea.append( counter + "! = " +21 factorial( counter ) + "\n" );22 23 } // end method init24

Invoke method factorial

Page 42: Bölüm  6 – Metod lar ve Parametreler

FactorialTest.java

Lines 29-30Test for base case (method factorial can solve base case)

Line 34Else return simpler problem that method factorial might solve in next recursive call

25 // recursive declaration of method factorial 26 public long factorial( long number ) 27 { 28 // base case 29 if ( number <= 1 ) 30 return 1; 31 32 // recursive step 33 else 34 return number * factorial( number - 1 );35 36 } // end method factorial 37 38 } // end class FactorialTest

Test for base case (method factorial can solve base case)

Else return simpler problem that method factorial might solve

in next recursive call

Page 43: Bölüm  6 – Metod lar ve Parametreler

6.13 Yineleme Problemlerine Örnek The Fibonacci Series

• Fibonacci series– Each number in the series is sum of two previous numbers

• e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21…

fibonacci(0) = 0 fibonacci(1) = 1fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 2 )

• fibonacci(0) and fibonacci(1) are base cases– Golden ratio (golden mean)

Page 44: Bölüm  6 – Metod lar ve Parametreler

FibonacciTest.java

1 // Fig. 6.16: FibonacciTest.java2 // Recursive fibonacci method.3 import java.awt.*;4 import java.awt.event.*;5 6 import javax.swing.*;7 8 public class FibonacciTest extends JApplet implements ActionListener {9 JLabel numberLabel, resultLabel;10 JTextField numberField, resultField;11 12 // set up applet’s GUI13 public void init()14 {15 // obtain content pane and set its layout to FlowLayout16 Container container = getContentPane();17 container.setLayout( new FlowLayout() );18 19 // create numberLabel and attach it to content pane20 numberLabel = new JLabel( "Enter an integer and press Enter" );21 container.add( numberLabel );22 23 // create numberField and attach it to content pane24 numberField = new JTextField( 10 );25 container.add( numberField );26 27 // register this applet as numberField’s ActionListener28 numberField.addActionListener( this ); 29

Page 45: Bölüm  6 – Metod lar ve Parametreler

FibonacciTest.java Line 43Method actionPerformed is invoked when user presses EnterLine 45We use long, because Fibonacci numbers become large quicklyLines 48-53Pass user input to method fibonacci

30 // create resultLabel and attach it to content pane31 resultLabel = new JLabel( "Fibonacci value is" );32 container.add( resultLabel );33 34 // create numberField, make it uneditable35 // and attach it to content pane36 resultField = new JTextField( 15 );37 resultField.setEditable( false );38 container.add( resultField );39 40 } // end method init41 42 // obtain user input and call method fibonacci43 public void actionPerformed( ActionEvent event )44 { 45 long number, fibonacciValue;46 47 // obtain user’s input and convert to long48 number = Long.parseLong( numberField.getText() );49 50 showStatus( "Calculating ..." ); 51 52 // calculate fibonacci value for number user input53 fibonacciValue = fibonacci( number ); 54 55 // indicate processing complete and display result56 showStatus( "Done." ); 57 resultField.setText( Long.toString( fibonacciValue ) );58 59 } // end method actionPerformed60

Method actionPerformed is invoked when user presses Enter

We use long, because Fibonacci numbers

become large quickly

Pass user input to method fibonacci

Page 46: Bölüm  6 – Metod lar ve Parametreler

FibonacciTest.java

Lines 65-66Test for base case (method fibonacci can solve base case)

Lines 69-70Else return simpler problem that method fibonacci might solve in next recursive call

61 // recursive declaration of method fibonacci 62 public long fibonacci( long n ) 63 { 64 // base case 65 if ( n == 0 || n == 1 ) 66 return n; 67 68 // recursive step 69 else 70 return fibonacci( n - 1 ) + fibonacci( n - 2 );71 72 } // end method fibonacci 73 74 } // end class FibonacciTest

Else return simpler problem that method fibonacci might solve

in next recursive call

Test for base case (method fibonacci can solve base case)

Page 47: Bölüm  6 – Metod lar ve Parametreler

FibonacciTest.java

Page 48: Bölüm  6 – Metod lar ve Parametreler

FibonacciTest.java

Page 49: Bölüm  6 – Metod lar ve Parametreler

Fig. 6.17 Set of recursive calls for fibonacci (3).

return

return

+

+ return 1

return 1

fibonacci( 2 ) fibonacci( 1 )

fibonacci( 1 ) fibonacci( 0 )

return 0

fibonacci( 3 )

Page 50: Bölüm  6 – Metod lar ve Parametreler

6.14 Yineleme ve Döngüler

• Döngüler– Döngü deyimleri kullanılır (for, while veya do…while)– Döngü bitişi şart ile kontrol edilir.– Sayaç kullanarak döngü kontrol edilir.

• Yineleme– Seçim deyimleri kullanılır (if, if…else veya switch)– Tekrarlama metdodun yeniden çağrılması ile olur.– İlk değer önem taşır– Problem küçük kısımlara ayrılarak tekrarlama kontrol edilir.

Page 51: Bölüm  6 – Metod lar ve Parametreler

6.14 Yineleme ve Döngüler

• Yineleme– Döngülerden daha fazla ek yük getirir.– Daha fazla bellek harcanır– Genelde birkaç satır kod ile problem çözülür.