Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Bölüm 5 – Kontrol İfadeleri : 2.Kısım İçerik 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 Giriş Bir Kontrollü Döngü İfadesinde Olması Gerekenler for Döngü Deyimleri for Döngü Deyimi ile alakalı Örnekler do…while Döngü Deyimi switch Çok Seçmeli Komut break ve continue Komutları Etiketli break ve continue Komutları Mantıksal Operatörler Yapısal Programlama Özeti 5.1 Giriş • Yapısal programlama komutlarına devam ediyoruz. – Java’nın kontrol komutlarını hatırlayalım 5.2 Bir Kontrollü Döngü İfadesinde Olması Gerekenler • Sayaç-kontrollü döngü : – – – – Kontrol değişkeni (döngü sayacı) Kontrol değişkenine ilk değer verme Her dönüşte kontrol değişkenini artırma/azaltma Kontrol değişkeninin son değere ulaşıp ulaşmadığını döngüdeki şart ile tesbiti for Döngü Komutu 5.3 for anahtar kelime Kontrol değişkeni Noktalı virgül ile ayrım Kontrol değişkenin son değeri Noktalı virgül ie ayrım for ( int counter = 1; counter <= 10; counter++ ) Kontrol değişkenin ilk değeri Fig. 5.3 Döngünün şartı Kontrol değişkenin bir artımı for deyiminin ayrıntılı anlatımı. 5.3 for Döngü Yapısı for ( ilk değer verme; döngü şartı; artış ) { komutlar; } Aynı ifade aşağıdaki gibi de yazılabilir: İlk değer verme; while ( döngü şartı ) { komutlar; artış; } 5.4 for İfadeleri için Örnekler • for deyiminde kontrol değişkenin değişimi – Kontrol değişkenini 1’den başlatıp 100 ‘e varıncaya kadar 1 artışla ilerletecek for deyimi • for ( int i = 1; i <= 100; i++ ) – Kontrol değişkenini 100’den başlatıp 1‘e varıncaya kadar 1’er 1’er azaltıp ilerletecek for deyimi • for ( int i = 100; i >= 1; i-- ) – Kontrol değişkenini 7’den başlatıp 7’şer artışla 77 kadar ilerlecek for deyimi • for ( int i = 7; i <= 77; i += 7 ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 5.5: Sum.java // 1’den 100’e kadar çift sayıların toplamı. import javax.swing.JOptionPane; increment number by 2 each iteration public class Toplam { public static void main( String args[] ) { int toplam = 0; // ilk değer verme // 2 den 100’e kadar çift sayıların toplamı for ( int sayi = 2; sayi <= 100; sayi += 2 ) toplam += sayi; // display results JOptionPane.showMessageDialog( null, “Toplam " + toplam, "Total Even Integers from 2 to 100", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class Sum // terminate application Sum.java Line 12 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 26 // Fig. 5.6: Interest.java // Calculating compound interest. import java.text.NumberFormat; // class for numeric formatting Java treats floating-points as import java.util.Locale; // class for country-specific information import javax.swing.JOptionPane; import javax.swing.JTextArea; Interest.java type double NumberFormat can format numeric values as currency Lines 13-15 public class Interest { Display public static void main( String args[] ) currency values with { dollar sign ($) double amount; // amount on deposit at end of each year double principal = 1000.0; // initial amount before interest double rate = 0.05; // interest rate // create NumberFormat for currency in US dollar format NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US ); // create JTextArea to display output JTextArea outputTextArea = new JTextArea(); // set first line of text in outputTextArea outputTextArea.setText( "Year\tAmount on deposit\n" ); Line 18 Line 19 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year amount = principal * Math.pow( 1.0 + rate, year ); // append one line of text to outputTextArea outputTextArea.append( year + "\t" + moneyFormat.format( amount ) + "\n" ); } // end for // display results JOptionPane.showMessageDialog( null, outputTextArea, "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class Interest // terminate the application Calculate amount with for Interest.java statement Lines 28-31 5.5 do…while Döngü İfadesi • do…while yapısı – while komutuna benzer. – Bu döngü yapısında döngü içindeki blok en az bir defa çalışır. Blok kodları [true] şart [false] Fig. 5.8 do…while akış diyagramı. 5.6 switch Çok-Şeçmeli Yapılar • switch deyimi – Çok seçmeli zamanlar için kullanılır 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 26 27 28 29 30 31 // Fig. 5.9: SwitchTest.java // Drawing lines, rectangles or ovals based on user input. import java.awt.Graphics; SwitchTest.java import javax.swing.*; public class SwitchTest extends JApplet { int choice; // user's choice of which shape to draw // initialize applet by obtaining user's choice public void init() { Get user’s String input; // user's input input in JApplet // obtain user's choice input = JOptionPane.showInputDialog( "Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" + "Enter 3 to draw ovals\n" ); choice = Integer.parseInt( input ); // convert input to int } // end method init // draw shapes on applet's background public void paint( Graphics g ) { super.paint( g ); // call paint method inherited from JApplet for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9) Lines 16-21: Getting user’s input 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 switch ( choice ) { // determine shape to draw user input (choice) is case 1: // draw a line switch statement determines controlling expression g.drawLine( 10, 10, 250, 10 + i * 10 ); SwitchTest.java which case label to execute, break; // done processing case case 2: // draw a rectangle g.drawRect( 10 + i * 10, 10 + i 50 + i * 10, 50 + i * 10 ); break; // done processing case depending on controlling expression Line 32: controlling * 10, expression case 3: // draw an oval g.drawOval( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 ); break; // done processing case Line 32: switch statement Line 48 default: // draw string indicating invalid value entered g.drawString( "Invalid value entered", 10, 20 + i * 15 ); } // end switch } // end for } // end method paint } // end class SwitchTest default case for invalid entries SwitchTest.java SwitchTest.java [true] case a case a action(s) break case b action(s) break case z action(s) break [false] [true] case b [false] . . . [true] case z [false] default action(s) Fig. 5.10 break komutu ile switch akış diyagramı. 5.7 break ve continue deyimleri • break/continue – Programın akış sırasını değiştirir. • break deyimi – Kontrol yapısından çıkışı sağlar. • while, for, do…while or switch ifadelerinde kullanılır • continue deyimi – Döngünün başına döner. – while, for or do…while ifadelerinde kullanılır. 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 26 27 28 // Fig. 5.11: BreakTest.java // Terminating a loop with break. import javax.swing.JOptionPane; BreakTest.java public class BreakTest { public static void main( String args[] ) { Loop String output = ""; int count; for ( count = 1; count <= 10; count++ ) { if ( count == 5 ) break; exit for structure (break) Line 12 when count equals 5 10 times Lines 14-15 // loop 10 times // if count is 5, // terminate loop output += count + " "; } // end for output += "\nBroke out of loop at count = " + count; JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); } // end main } // end class BreakTest // terminate application 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 26 27 // Fig. 5.12: ContinueTest.java // Continuing with the next iteration of a loop. import javax.swing.JOptionPane; public class ContinueTest { public static void main( String args[] ) { String output = ""; ContinueTest.ja Skip line 16 and proceed va to line 11 when count equals 5 Line 11 Loop 10 times for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) continue; // loop 10 times // if count is 5, // skip remaining code in loop output += count + " "; } // end for output += "\nUsed continue to skip printing 5"; JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class ContinueTest Lines 13-14 5.8 Etiketli break ve continue İfadeleri • Etiketli blok – {} arasındaki kodlar – Parantez öncesi blokğu adalandırıcı etiket • Etiketli break ifadesi – İçinde bulunduğu bloktan çıkmasını sağlar. – Blok sonından çalışmaya devam eder. • Etiketli continue ifadesi – Blok içindeki kodları atlar – Etiketin başına gelerek programa devam eder. 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 26 27 28 29 // Fig. 5.13: BreakLabelTest.java // Labeled break statement. import javax.swing.JOptionPane; public class BreakLabelTest { stop is the labeled block public static void main( String args[] ) { String output = ""; stop: { Loop 10 times // count 10 rows for ( int row = 1; row <= 10; row++ ) { Nested loop 5 times // count 5 columns for ( int column = 1; column <= 5 ; column++ ) { output += "* output += "\n"; } // end outer for // if row is 5, // jump to end of stop block "; } // end inner for Line 11 Line 14 // labeled block if ( row == 5 ) break stop; BreakLabelTest. java Exit to line 35 (next slide) Line 17 Lines 19-20 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // following line is skipped output += "\nLoops terminated normally"; } // end labeled block JOptionPane.showMessageDialog( null, output, "Testing break with a label", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class BreakLabelTest BreakLabelTest. java 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 26 27 28 // Fig. 5.14: ContinueLabelTest.java // Labeled continue statement. import javax.swing.JOptionPane; public class ContinueLabelTest { nextRow is the labeled block public static void main( String args[] ) { String output = ""; nextRow: Loop 5 times Line 11 Line 14 // target label of continue statement // count 5 rows for ( int row = 1; row <= 5; row++ ) { output += "\n"; ContinueLabelTe st.java Nested loop 10 times Line 17 Lines 21-22 // count 10 columns per row for ( int column = 1; column <= 10; column++ ) { // if column greater than row, start next row if ( column > row ) continue nextRow; // next iteration of labeled loop output += "* "; } // end inner for } // end outer for continue to line 11 (nextRow) 29 30 31 32 33 34 35 36 37 38 JOptionPane.showMessageDialog( null, output, "Testing continue with a label", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class ContinueLabelTest ContinueLabelTe st.java 5.9 Mantısal Operatörler • Mantıksal operatörler – Daha karışık şartlar oluşturmak amaçlı – Basit şartları birleştirmek amaçlı kullanılır. • Java mantıksal operatörler – – – – – – && & || | ^ ! (koşul AND) (mantıksal AND) (koşul OR) (mantıksal OR) (dışlayan OR) (mantıksal NOT) expression1 && expression2 false false false false true false true false false true true true Fig. 5.15 && (conditional AND) operator truth table. expression1 expression2 expression1 || expression2 false false false false true true true false true true true true Fig. 5.16 || (conditional OR) operator truth table. expression1 expression2 expression1 ^ expression2 false false false false true true true false true true true false Fig. 5.17 ^ (boolean logical exclusive OR) operator truth table. expression1 expression2 expression !expression false true true false Fig. 5.18 ! (logical negation, or logical NOT) operator truth table. 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 26 27 28 // Fig. 5.19: LogicalOperators.java // Logical operators. import javax.swing.*; LogicalOperator s.java public class LogicalOperators public static void main( String args[] ) { // create JTextArea to display results JTextArea outputArea = new JTextArea( 17, 20 ); Lines 16-20 Lines 23-27 // attach JTextArea to a JScrollPane so user can scroll results JScrollPane scroller = new JScrollPane( outputArea ); Conditional AND truth table // create truth table for && (conditional AND) operator String output = "Logical AND (&&)" + "\nfalse && false: " + ( false && false ) + "\nfalse && true: " + ( false && true ) + "\ntrue && false: " + ( true && false ) + "\ntrue && true: " + ( true && true ); Conditional OR truth table // create truth table for || (conditional OR) operator output += "\n\nLogical OR (||)" + "\nfalse || false: " + ( false || false ) + "\nfalse || true: " + ( false || true ) + "\ntrue || false: " + ( true || false ) + "\ntrue || true: " + ( true || true ); 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // create truth table for & (boolean logical AND) operator output += "\n\nBoolean logical AND (&)" + "\nfalse & false: " + ( false & false ) + "\nfalse & true: " + ( false & true ) + "\ntrue & false: " + ( true & false ) + Boolean logical "\ntrue & true: " + ( true & true ); AND LogicalOperator s.java truth table Lines // create truth table for | (boolean logical inclusive OR) operator output += "\n\nBoolean logical inclusive OR (|)" + "\nfalse | false: " + ( false | false ) + Lines "\nfalse | true: " + ( false | true ) + "\ntrue | false: " + ( true | false ) + Boolean logical inclusive Lines "\ntrue | true: " + ( true | true ); 30-34 37-41 44-48 OR truth table // create truth table for ^ (boolean logical exclusive OR) operator Lines output += "\n\nBoolean logical exclusive OR (^)" + "\nfalse ^ false: " + ( false ^ false ) + "\nfalse ^ true: " + ( false ^ true ) + "\ntrue ^ false: " + ( true ^ false ) + Boolean logical exclusive "\ntrue ^ true: " + ( true ^ true ); OR truth table // create truth table for ! (logical negation) operator output += "\n\nLogical NOT (!)" + "\n!false: " + ( !false ) + "\n!true: " + ( !true ); Logical NOT truth outputArea.setText( output ); table // place results in JTextArea 51-53 57 58 59 60 61 62 63 64 JOptionPane.showMessageDialog( null, scroller, "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class LogicalOperators LogicalOperator s.java Operators Associativity Type ++ -right to left unary postfix ++ -- + ! right to left unary (type) * / % left to right multiplicative + left to right additive < <= > >= left to right relational == != left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR | left to right boolean logical inclusive OR && left to right conditional AND || left to right conditional OR ?: right to left conditional = += -= *= /= %= right to left assignment Fig. 5.20 Precedence/associativity of the operators discussed so far. 5.10 Yapısal Programlama (Özet) • Sıralı Yapılar – Java daki yerleşik ifadeler • Seçimli Yapılar – if, if…else ve switch • Tekrarlana Yapılar – while, do…while ve for Sıralı Seçimli if statement (single selection) switch statement (multiple selection) [t] [t] break [f] [f] [t] if else statement (double selection) [f] break . . . [t] [t] break [f] default Tekrarlı while statement do while statement for statement [t] [t] [f] [t] [f] [f] Fig. 5.21 Java’s single-entry/single-exit sequence, selection and repetition statements. Rules for Forming Structured Programs 1) Begin with the “simplest activity diagram” (Fig. 5.23). 2) Any action state can be replaced by two action states in sequence. 3) Any action state can be replaced by any control statement (sequence, if, if else, switch, while, do while or for). 4) Rules 2 and 3 can be applied as often as you like and in any order. Fig. 5.22 Rules for forming structured programs. action state Fig. 5.23 En basit akış diyagramı. apply Rule 2 action state apply Rule 2 apply Rule 2 action state action state action state action state action state . . . action state action state Fig. 5.24 En basit akış diyagramına kural 2 ‘yi uygulayıcı yeni sıralı komutlar ekleniyor. apply Rule 3 action state [f] apply Rule 3 action state [f] [f] action state [t] action state [t] action state apply Rule 3 [t] [f] action state [t] action state Fig. 5.25 Basit akış diyagramına kural 3 yani kontrol ve tekrarlı yapıları akleyebilirz. action state action state action state Fig. 5.26 Hatalı akış diyagramı. action state