Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Coding 2 David Davenport Computer Eng. Dept.,

Similar presentations


Presentation on theme: "Java Coding 2 David Davenport Computer Eng. Dept.,"— Presentation transcript:

1 Java Coding 2 David Davenport Computer Eng. Dept.,
Decisions, decisions… David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Last updated: 22/10/2016 ~ added proper intro, etc. (fixed examples 4 slide messed up by powerpoint 2016?) ~ tweaked other slides & animation to make clearer! ~ separate slide for comparıng non-primitive (Strings) & reals ~ added Testing slide to end. Previous: 10/10/ & 8/10/2012 ~ Minor revisions

2 IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

3 Decisions, decisions… Do one thing or another (never both!)
Everyday examples: If it’s the weekend then stay in bed otherwise get up and go to class! If rain is forecast then take an umbrella If it’s sunny then take sunglasses & hat If married with two or more children then tax allowance is else tax allowance is 15000

4 space between “if” & “(“
Decision The Java if statement space between “if” & “(“ if (condition) statementT; else statementF; if (condition) statementT; Draw these in flowchart form too? where statement is any Java statement condition is a boolean expression

5 Conditions Any expression with boolean result boolean variable
canVote taxable found Method with boolean result exists( filename) isSent( my ) Operand relationalOperator Operand (where relationalOperator is: >, <, >=, <=, ==, != ) age >= speed != year % 4 == 0 Boolean expressions combined with logicalOperator (where logicalOperator is: &&, ||, ! ) height > 2 && weight <= x < 5 || x > 10 ! exists( filename) aChar >= ‘0’ && aChar <= ‘9’ Note, in particular, the use of == as opposed to = Relational operators also work for char & boolean Ordering is defined by Unicode for char Note: cannot write “0 <= x < 10” must say “x >= 0 && x < 10” For non-primitive types, == & != will compile but may not always give the expected result! For String’s use: string1.equals( string2) or string1.equalsIgnoreCase( string2) Also for ordering use: string1.compareTo( string2) { neg., zero, pos. result} (compares using code values… digits, then capital letters, then lowercase, etc,) The last example tests whether aChar contains a digit or not by comparing the ASCII codes. Similarly used to test for Letters and to convert between upper & lower case, But, only works for English. In Java, use Character.isDigit( ch); Character.isDigit( ch), isLetter( ch), isUpperCase( ch), isWhiteSpace( ch), & Character.toUpperCase( ch); etc. Emphasize… No need for the “== true” in “if ( x > 0 == true)” or “if ( canVote == true)” And “if ( x > 0 == false)” or “if ( canVote == false)” is equally bad, it’s both unnecessary & inelegant! Rewrite as “if ( x <= 0)” or “if ( !canVote)” Note: discuss comparing reals?

6 Examples (1) Print message when x is positive
if ( x > 0 ) System.out.println( “The value of x is positive”); Print warning if oil pressure is below a specified limit if ( oilPressure < MINIMIUM_OIL_PRESSURE ) System.out.println( “Warning – low oil pressure!”); Report whether x is negative or not if ( x < 0 ) System.out.println( “Negative”); else System.out.println( “Positive or zero”); Rewrite with alternative condition? Rewrite English into pseudocode first to emphasize start with algorithm step and then translate to Java e.g. Print message when x is positive becomes If x is positive then report “value of x is positive” And so if ( x > 0) System.out.println( “x is positive”); Note: relational operators only work with primitive types… for non-primitive types such as String, use .equals & .compareTo

7 Examples (1) …caution! Checking non-primitive types… e.g. user’s password if (enteredPassword == actualPassword) // do secure things! else System.out.println( “Sorry, incorrect Password”); if ( !actualPassword.equals( enteredPassword) ) System.out.println( “Sorry, incorrect Password”); else // do secure things! Checking real values… e.g. circumference! if ( circumference == 31.42) System.out.println( “Spot on!” ); if ( (circumference ) < ) System.out.println( “Close enough!” ); Tip: In terms of style/ease of reading… putting the single line error message first (in the then part) is clearer since it is right next to the condition that it relates too. Caution: (assuming s1 & s2 are non-primitive types, e.g. Strings…) s1 == s2 ~~ compiles, but may not work as expected s1 <= s2 ~~ will not even compile! For non-primitive types… equality can have several different meanings (will understand when do Objects later)! just use .equals for now. comparison/ordering… (can’t do using <, >, etc.) relational operators only work with primitive types for non-primitive types such as String, use .compareTo Tip: when comparing Strings, can also use .equalsIgnoreCase & .compareToIgnoreCase Comparing real types for exact equality is dodgy too… always test for range or allow for slight imprecision. (have circumference because of surprise in circle computer output!) (should be absolute value of difference less than epsilon.) oops… not quite right!!

8 & negations of each form,
Examples (2) Compute z as absolute value of x-y if ( x – y < 0 ) z = y – x; else z = x – y; if ( x > y ) z = x - y; else z = y - x; z = x – y; if ( z < 0 ) z = -z; x 3 5 2 5 3 2 y z Can use z = Math.abs(x-y); Obviously can negate each case too, e.g. if ( x <= y ) z = y - x; else z = x - y; But for last one… z = x – y; if ( z >= 0 ) z = z; // by analogy? = do nothing! else z = -z; Which is silly, so when seen convert back to version on slide! z = x – y; if ( z >= 0 ) _______ else z = -z; & negations of each form, except last?

9 Getting too messy? Then try starting over…
Examples (3) Given three values stored in variables first, second, third, store the minimum in a variable called min if ( first < second ) min = first; else min = second; if ( third < min ) min = third; Generalise…? first second min 5 3 Try starting with smaller problem… Begin with simplest case, that of two variables, then work up! Each additional “input” variable, e.g. third, fourth, requires another if statement to differentiate it from current smallest and so set min appropriately. This gets increasingly messy… (more and more levels of indentation). Time to rethink, perhaps? Might write condition of simple solution with wrong condition first, i.e. write the following to emphasize previous point again! if (min < third) min = min; // oops… rewrite! else min = third; Note, could compare first & second, then first & third, & second & third. if ( first < second && first < third) min is first else if (third < first && third < second) min is third else if ( second < first && second < third) min is second Note: might also use: min = Math.min( first, Math.min( second, third) ); Getting too messy? Then try starting over…

10 Examples (4) Avoid divide-by-zero errors In Java..?
if y is zero then output error msg else compute z as x / y report z In Java..? if ( y = 0 ) System.out.println( “Error: can’t divide by zero”); else z = x / y; System.out.println( “The result is “ + z ); In exam average problem we had to avoid dividing by zero… compute average as sum of all papers / number of papers General form is… if y is zero then output error msg else compute z as x / y report z Proposed Java on slide… Obvious syntax error – should be if (y == 0) … Note that this will not work correctly, but will not give a compile error! Remember, Java ignores white space! Need curly brackets to form compound statement block. Compound statements can be used wherever Java syntax calls for a statement, e.g. in the then or else clauses of an if statement. if ( y == 0 ) System.out.println( “Error: can’t divide by zero”); else z = x / y; System.out.println( “The result is “ + z );

11 Examples (4) continued…
Use braces (curly brackets) to form compound statement { statement; : } statement; Avoid divide-by-zero errors if ( y == 0 ) System.out.println( “Error: can’t divide by zero”); else { z = x / y; System.out.println( “The result is “ + z ); }

12 Examples (5) Choosing between three alternatives:
if ( x < 0 ) System.out.println( “Negative”); else { if ( x == 0 ) System.out.println( “Zero”); else System.out.println( “Positive”); } if ( x >= 0 ) if ( x == 0 ) System.out.println( “Zero”); else System.out.println( “Positive”); else System.out.println( “Negative”); Note that, both examples work ok with or without the curly brackets. This is possible since an if statement is a single Java statement so either the true or false clause of an if statement can be replaced by another if statement. The else clause is always associated with the closest if, assuming there are no curly brackets. In the second example, removing the first else & print “Positive” will result in seemingly weird behaviour, but no syntax error!

13 Examples (6) A neater way of writing mutually exclusive alternatives (nested if): if ( x < 0 ) System.out.println( “Negative”); else if ( x == 0 ) System.out.println( “Zero”); else if ( x < 5) System.out.println( “1 – 4 inclusive”); else System.out.println( “>= 5”); // & x >= 0 // & x >= 0 & x != 0 // & x >= 0 & x != 0 & x >= 5 The layout is much clearer and easily to read. It offers an identifiable set of mutually exclusive alternatives, i.e. one and only one of them will be chosen. Easily extend to more alternatives. Note the implied conditions at each step. No need to write last if at all! (differentiate implicit conditions ~in red~ vs. explicit conditions ~in black~)

14 Distinguish… if (cond) print “A” else if (cond)
print “B” else if (cond) print “C” else print “D” if (cond) print “A” if (cond) print “B” if (cond) print “C” if (cond) print “D” The first (a nested if) will select one and only one of A, B, C & D. The second may do any combination of them, including all or none. Tip: can avoid input exception by using scan.hasNextInt(), etc. Note: There is also the “switch” statement in Java. We will not use it (leftover from hardware… dangerous, easy to forget break!) We will not use the conditional operator either (shorthand, but not easy to read)

15 Testing… Test data helps check design and implementation
Testing code having “if” statements Coverage cases to exercise both true & false options Boundary conditions cases to check condition really switches in right place if condition ~~~~~~ else


Download ppt "Java Coding 2 David Davenport Computer Eng. Dept.,"

Similar presentations


Ads by Google