1 / 32

Metod lar ve Parametreler

Metod lar ve Parametreler.

maik
Download Presentation

Metod lar ve Parametreler

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Metodlar ve Parametreler menüJava’da Program ModuleriMath-Class MetodlarıMethod TanıtımıArgumanın Veri Tipi Yükseltmesi Random-Sayı ÜretmekErişim AlanlarıJAppletSınıfının MetodlarıMethod Overloading(Aşırı Yükleme )YinelemeYineleme Problemlerine Örnek: The Fibonacci SeriesYineleme ve Döngüler

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

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

  4. yönetici işçi1 işçi4 işçi2 işçi5 işçi3 Yönetici-metod / işçi metod arasındaki hiyerarşik ilişki.

  5. 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 Mathsınıfına ait • Nokta (.) sqrtmethoduna erişimi sağlıyor. • Argument900.0 iseparantez içine yazılır.

  6. 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. • globaldeğ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.

  7. import java.applet.*; import java.awt.*; public classkareAlmaextends 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; // return square of y } // end karesi }

  8. 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 returndeğerleri de olabilir: returndeğer;

  9. // Üçgen çizdirme programı import java.awt.*; import java.applet.Applet; public classucgenCizextends 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, tabanY-height); g.drawLine(tabanX+ taban/2, tabanY-height, tabanX, tabanY); } }

  10. // Üçgen çizdirme metodu import java.awt.*; import java.applet.Applet; publicclass 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); } }

  11. 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 }

  12. // Ev çizimi import java.awt.*; import java.applet.Applet; publicclass x extends Applet { publicvoid paint(Graphics g) { evCiz(g,50,50, 70,30); evCiz(g,100,50,60,20); } privatevoid 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,tabanY-yukseklik); g.drawLine(tabanX+taban/2,tabanY-yukseklik, tabanX,tabanY); } privatevoid 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); } }

  13. 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ızK=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?

  14. 1 // MaximumTest.java// ondalılı 3 sayının en büyüğü. 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 GUI 10 public void init() 11 { 12 // obtain user input 13 String s1 = JOptionPane.showInputDialog( 14 “1.sayıyı giriniz(ondalıklı)" ); 15 String s2 = JOptionPane.showInputDialog( 16 " 2.sayıyı giriniz(ondalıklı) " ); 17 String s3 = JOptionPane.showInputDialog( 18 " 3.sayıyı giriniz(ondalıklı) " ); 19 20 // convert user input to double values 21 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 call double min = manimum( number1, number2, number3 ); // method call 26 27 // create JTextArea to display results 28 JTextArea outputArea = new JTextArea(); 29 30 // display numbers and maximum value 31 outputArea.setText( "number1: " + number1 + "\nnumber2: " + 32 number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );

  15. // yazı alanını göstermek için applet kullanıcı arayüzü bileşenlerini kullan 35 Container c = getContentPane(); 36 //container: kap,yüklenici anlamında 37 // Container c ye outputAraea nesnensini ekle 38 c.add( outputArea ); 39 40 } // end method init 41public double minumum( double x, double y, double z ) 45 { 46 return Math.min( x, Math.min( y, z ) ); 47 48 } // en metod min 42 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

  16. Random-Sayı Üretme • Java random-sayı üreticisi • Math.random() • ( int ) ( Math.random() * 6 ) • 0 ile 5 arası integer sayı üretir.

  17. 1 // RandomIntegers.java 2 // 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 times 13 for ( int counter = 1; counter <= 20; counter++ ) { 14 15 // 1 ve 6 arasında rastgele integer sayı 16 value = 1 + ( int ) ( Math.random() * 6 ); 17 18 output += value + " "; // append value to output 19 20 // if counter divisible by 5, append newline to String output 21 if ( counter % 5 == 0 ) 22 output += "\n"; 23 24 } // end for 25

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

  19. JAppletSınıfının Metodları • Java API birçok JApplet metodları tanımlamıştır. • Bu metodları yeniden JApplette tanıtmaya overriding (eskisini geçersiz kılma)denir.

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

  21. // MethodOverload.java// overloaded (aşırı yüklenmiş) metodlar kullanma 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 intkaresi( 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 doublekaresi( 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ı

  22. import java.awt.Graphics; import javax.swing.JApplet; publicclass asiriYukleme extends JApplet{ publicvoid 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); } publicint karesi( int x ) { return x * x; } publicdouble karesi( int x ) { return x * x; } }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 MethodOverload.java:15: square(int) is already defined in MethodOverload public double square( int y ) ^ 1 error

  23. 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ı

  24. 5! 1 5! 1 Final value = 120 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 (b) Values returned from each recursive call. (a) Sequence of recursive calls. Fig. 6.14 Recursive evaluation of 5!.

  25. 1 // Fig. 6.15: FactorialTest.java 2 // 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-10 11 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 10 19 for ( long counter = 0; counter <= 10; counter++ ) 20 outputArea.append( counter + "! = " +factorial( counter ) + "\n" ); 22 23 } // end method init 25 // recursive declaration of method factorial 26 public long factorial( long number ) 27 { 28 // base case 29 if ( number <= 1 ) 30 return1; 32 // recursive step 33 else 34 return number * factorial( number - 1 ); 35 36 } // end method factorial 37 38 } // end class FactorialTest

  26. 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) = 1fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 2 ) • fibonacci(0) and fibonacci(1) are base cases • Golden ratio (golden mean)

  27. 1 // Fig. 6.16: FibonacciTest.java// Recursive fibonacci method. 3 import java.awt.*; 4 import java.awt.event.*;// enter eventi 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 GUI 13 public void init() 14 { 15 // content pane tanmla ve layout(yerleşim) olarak FlowLayout set et 16 Container container = getContentPane(); 17 container.setLayout( new FlowLayout() ); 18 19 // label tanımla ve konteynıra ekle 20 numberLabel = new JLabel( “integer sayı giriniz ve enter a basınız" ); 21 container.add( numberLabel ); 22 23 // sayı girilebilecek text alanı tanımla ve konteynıra ekle 24 numberField = new JTextField( 10 ); 25 container.add( numberField ); 26 27 // numberField ın ActionListener ( hareket listesini) bu aplete ekle 28 numberField.addActionListener( this );

  28. 30 // sonuc labelı oluştur ve conteynıra ekle 31 resultLabel = new JLabel( "Fibonacci değeri" ); 32 container.add( resultLabel ); 33 34 // text alanı oluştur, ve edit edilmesini engelle ve konteynıra ekle 35 resultField = new JTextField( 15 ); 37 resultField.setEditable( false ); 38 container.add( resultField ); 39 40 } // end method init 41 42 // kullanıcı entera basınca bu metod tetkilencek 43 public void actionPerformed( ActionEvent event ) 44 { 45 long number, fibonacciValue; 46 number = Long.parseLong( numberField.getText() ); 49 //işlem devam ediyor, statusbar( durum çubuğunda) 50 showStatus( “hesaplanıyor ..." ); 51 52 // girilen sayı için fibonacci değerini hesapla 53 fibonacciValue = fibonacci( number ); 54 55 // işlemin tamamnladığını göster 56 showStatus( “tamamlandı." ); 57 resultField.setText( Long.toString( fibonacciValue ) ); 58 59 } // end method actionPerformed

  29. 61 // fibonacci metodu recursif(kendini açğıran )olarak tanımla 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

  30. fibonacci( 3 ) return fibonacci( 2 ) fibonacci( 1 ) + + return fibonacci( 1 ) fibonacci( 0 ) return 1 return 0 return 1 Fig. 6.17 Set of recursive calls for fibonacci(3).

More Related