PERCABANGAN Bagaimana Jika YA Bagaimana Jika TIDAK Bagaimana
PERCABANGAN Bagaimana Jika YA? Bagaimana Jika TIDAK? Bagaimana Jika BENAR? Bagaimana jika SALAH?
Catch-up Exercise • Buat program java untuk menghitung luas segi tiga. • Tes program dengan input: • Alas = 20, tinggi = 10 • Alas = 10, tinggi = -30 2
Flow of Control • Flow of Control Cara kerja komputer memproses perintah dalam sebuah program: – Sequentially; baris per baris, – Conditionally; dengan perintah percabangan – Repetitively; menggunakan perintah perulangan • Program yang selama ini dibuat adalah sekuensial. • Dalam slide ini akan dibahas jenis Kondisional. 3
Perintah Seleksi • Selection or branching statement menentukan the action that should be taken by the computer. • Titik dimana a decision has to be made as to jalur yang akan diambil. yes <buy a house> <buy a car> <give to charity> IF <Saya punya uang 1 M> no no <ambil kredit> <baik ke semua orang> <perbanyak doa> 4
Perintah if-else • In Java, we can write a selection statement using if-else • Syntax: if <ekspresi boolean > <statement_1> else <statement_2> • Jika ekspresi boolean bernilai true, maka statement_1 yang akan dieksekusi. • Jika ekspresi boolean bernilai false, maka statement_2 yang akan dieksekusi. 5
Example 1 • • Perhatikan fragmen program berikut ini: int age; Scanner keyboard = new Scanner (System. in); age = keyboard. next. Int(); if (age < 21) System. out. println("too young to vote"); else System. out. println("register as voter"); • What is the output if the user enters – 16 – 23 – 21 6
Example 2 count = 4; total = 5; if (count < 3) total = 0; else total = total + count; System. out. println(total); 7
Compound Statements • To include multiple statements in a branch, enclose the statements in braces. if (count < 3) { total = 0; count = 0; } 8
Menghilangkan Bagian else • Jika bagian else dihapus and the expression after the if is false, no action occurs. • syntax if (Boolean_Expression) Statement • example weight = 50; ideal = 60; if (weight > ideal) calories. Per. Day -= 500; //kalori = kalori-500; 9
Ekspresi Boolean • When processing a selection statement such as an if statement, the computer must evaluate a boolean expression. • Recall the boolean primitive data type that holds the value true or false. • A boolean expression is sebuah ekspresi yang menghasilkan nilai true or false. • Boolean expressions biasanya memakai operator perbandingan (also known as relational operators) 10
Operators Perbandingan 11
Exercise [Latihan] 1. Write a Java program that asks the user for a score and displays "You pass" if the score is greater than or equal to 50 and "You fail" otherwise. 2. Write a Java program that asks the user for a grade and displays "Wow!" if the grade is 'A' and "Try harder next time" otherwise. 12
Operator Logika • Formula ekspresi boolean seringkali menjadi kompleks. • Modifikasilah program sebelumnya, so that it will display "You pass" if the assignment score is greater than or equal to 50 DAN the examination score is greater than or equal to 60. • We will need to use operator logika for more complex boolean expressions: – && (and) – || (or) – ! (not) 13
Truth Table/ Tabel Kebenaran • Refer to the following truth table for logical operators, assuming P and Q are boolean expressions: P Q P && Q P || Q !P !Q true false false true true false true 14
Presedensi Operator • We have looked at operator Arithmetic, operator Relational and Operator Logical. • Jika operators tersebut dipakai bersama dalam sebuah expression, they must be evaluated menurut the precedence rules: – – – – Parentheses (or brackets) Type cast (type) Logical not ! Arithmetic * / % Arithmetic + – +– Relational operators > >= < <= == != Logical AND and OR && || 15
Ekspresi Boolean Majemuk • Boolean expressions can be combined using the “or” (||) operator. • example if ((quantity > 5) || (cost < 10)). . . • syntax (Sub_Expression_1) || (Sub_Expression_2) 16
Compound Statements/ Perintah Majemuk • When a list of statements is enclosed in braces ({}), they form a single compound statement. • syntax { Statement_1; Statement_2; … } 17
Exercise • Evaluate the following expressions – (10 < 5) || (3 > 7) – !true && false – !(5==8) – true || !false – !(3 > 5 && 4 + 1 < 3 * 2) || 3 != 3 18
The if Statement • We can also use if without else: • Syntax: – if <boolean expression> <execute these statements> • If more than one statement is to be executed, they must be enclosed in curly brackets: if ((rich =='y') || (famous == 'y')) { System. out. println("I will be your friend"); System. out. println("You are either rich or famous"); } 19
Indentation • Important to improve the clarity of your program. • Show which statements are part of the if. • However, remember that indents are ignored by the compiler. • What is the output of the following program fragment for num = 8? num = 15? if (num < 10) num = num + 10; System. out. println("num is " + num); System. out. println("Finished!"); 20
Nested [bersarang] if • We can nest an if (or if-else) statement inside another if (or if-else) statement. • Consider the following: – Jika seorang mahasiswa adalah angkatan tahun 1, maka nilai lulusnya adalah 50, jika mahasiswa angkatan tahun 2, maka nilai lulusnya adalah 60 dan untuk angkatan tahun 3, maka nilai lulusnya adalah 40. • Write the code fragment to represent this. • Remember, every else must have an if (but not necessary vice-versa) 21
if-else pairs Example if (year == 1) if (mark >= 50) System. out. println("You pass"); else System. out. println("You fail"); else if (year == 2) if (mark >= 60) System. out. println("You pass"); else System. out. println("You fail"); else if (year == 3) if (mark >= 40) System. out. println("You pass"); else System. out. println("You fail"); else System. out. println("Cannot be determined"); nested if-else 22
Exercise • Write a Java program that will ask the user for a number and display the square root of the number if it is positive. – Use the Math. sqrt() method. • Next modify the program so that if the user enters a negative number, an error message will be displayed. 23
Exercise • Write a Java program that asks the user for his or her name and gender then displays "Hello Mr. xxx" or "Hello Ms. xxx" as appropriate. If an invalid value is entered for the gender, just return the name "xxx". 24
Nested Statements • An if-else statement can contain any sort of statement within it. • In particular, it can contain another if-else statement. – An if-else may be nested within the “if” part. – An if-else may be nested within the “else” part. – An if-else may be nested within both parts. 25
Nested Statements, cont. • Each else is paired with the nearest unmatched if. • If used properly, indentation communicates which if goes with which else. • Braces can be used like parentheses to group statements. 26
Nested Statements, cont. • syntax if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1) else Statement_2) else if (Boolean_Expression_3) Statement_3) else Statement_4); 27
Multibranch if-else Statements • syntax if (Boolean_Expression_1) Statement_1 else if (Boolean_Expression_2) Statement_2 else if (Boolean_Expression_3) Statement_3 else if … else Default_Statement 28
Multibranch if-else Statements, cont. • equivalent code 29
The switch Statement • The switch statement is a mutltiway branch that makes a decision based on an integral (integer or character) expression. • The switch statement begins with the keyword switch followed by an integral expression in parentheses and called the controlling expression. 30
The switch Statement, cont. • A list of cases follows, enclosed in braces. • Each case consists of the keyword case followed by – a constant called the case label – a colon – a list of statements. • The list is searched for a case label matching the controlling expression. 31
Switch Statement • The switch statement is a branching statement that allows multiple options. • This is similar to using nested if-else statements but it is simpler and often clearer. switch (gender) { case 'm': case 'M': System. out. println("Hello, Mr. " + name); break; case 'f': case 'F': System. out. println("Hello, Ms. " + name); break; default: System. out. println("Hello, " + name); break; } 32
Syntax – switch (variable / expression) { case label 1: statement; If the value of the break; variable /expression case label 2: matches the case label 3: label, the statements statement; following the label statement; will be executed break; until a break is case label 4: case label 5: reached. statement; break; optional section to be default: executed if none of statement; the case labels match break; the variable / } expression Must be of type byte, short, int or char ONLY Case label: • must be constant value • compatible type to the variable/ expression • cannot be duplicated 33
Exercise • Write a Java program that displays the following menu and allows the user to choose one of the options given. Then display the required nursery rhyme. Choose the rhyme: 1. winkle twinkle little star 2. Humpty Dumpty 3. London Bridge 4. Your choice? 2 5. Humpty Dumpty sat on the wall 6. Humpty Dumpty had a great fall 34
Java Character Set • Java uses unicode to represents characters. Unicode uses 2 bytes (16 bits) and are thus capable of representing a total of 65536 different symbols, but only half of these are used. • The first 256 unicode characters are the same as the ASCII characters. • All characters (whether unicode or ASCII) are represented using numerical code. – The character '0' is represented by the numerical code of 48, '9' 57, 'A' 65, 'a' 97, etc. • The expressions below are true: – – '3' < '9' '3' > 9 'B' > '4' 'a' > 'A' 35
Exercise • Write a program that asks the user to enter two grades, student 1 Grade and student 2 Grade. • The grade must be a character from 'A' to 'F'. If the grade for either student is lower than 'C' then display 'Help required'. • Then display whether student 1 or student 2 got the better grade. • Use methods in your program • Plan carefully! 36
- Slides: 36