Download presentation
Presentation is loading. Please wait.
1
Review of Previous Lesson
18/05/2019 Review of Previous Lesson State as many Vocabulary words and Learning Objectives that you remember from the last lesson as you can. Remember to grade yourself from
2
Conditionals & Control Flow
18/05/2019 Conditionals & Control Flow if, if/else, if/else if
3
Language Features and other Testable Topics
18/05/2019 Tested in the AP CS A Exam Notes Not tested in the AP CS A Exam, but potentially relevant/useful Operators Relational: ==, !=, <, <=, >, >= Numeric casts: (int), 1, 4 Control Statements if, if/else
4
Language Features and other Testable Topics
18/05/2019 Notes: 1. Students are expected to understand the operator precedence rules of the listed Operators. 4. Students are expected to understand “truncation towards 0” behaviour as well as the fact that positive floating-point numbers can be rounded to the nearest integer as (int) (x + 0.5), negative numbers as (int) (x - 0.5).
5
Types of Operator in Java
18/05/2019 Types of Operator in Java Basic Arithmetic Operators Assignment Operators Unary +, - Relational (comparison) operators Logical Operators (including Unary !) Unary Auto-increment & Auto-decrement Operators Concatenation Bitwise Operators Ternary Operator Types have been covered in previous presentations. Type 4 will be covered in this presentation.
6
5. Relational (comparison) operators
18/05/2019 ==, !=, >, <, >=, <= == Returns true if both the left side and right side are equal. != Returns true if left side is not equal to the right side of operator. > Returns true if left side is greater than right. < Returns true if left side is less than right side. >= Returns true if left side is greater than or equal to right side. <= Returns true if left side is less than or equal to right side.
7
Operator Precedence Rules
18/05/2019 Operator Associativity unary + - ! not associative cast () right to left multiplicative * / % left to right additive + - relational < <= > >= equality == != assignment = += -= *= /= %= Most programmers do not memorize these, and even those that do still use parentheses for clarity, so I am not sure why the AP syllabus mentions them. However, some programmers claim that too many brackets makes code more difficult to read. Associativity. When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. e.g. x = y = z = 17 is treated as x = (y = (z = 17)), leaving all 3 variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity. Some operators are not associative: for example, the expression (x <= y <= z) are invalid. Decreasing Precedence
8
Ranks of Operators 18/05/2019 ! +-(unary)(cast) * / % + -
Highest ! +-(unary)(cast) * / % < <= > >= == != Lowest
9
Boolean Conditions Two-way/Binary decisions.
18/05/2019 Boolean Conditions Two-way/Binary decisions. These decisions may seem small, but in programming, complicated decisions are made of many small decisions.
10
if(boolean condition){ Statement(s); }
18/05/2019 if(boolean condition){ Statement(s); } if The statements gets executed only when the given (boolean condition) is true. If the (boolean condition} is false then the {statements inside the if statement body} are completely ignored. Output: ?
11
Note about {} use in If statements
18/05/2019 Note about {} use in If statements { } are not needed for one line if statements: if ( booleanExpression ) statement; else ….. {} is optional for one line if statements but must be used for multiple line if statements: if ( booleanExpression ) { one or more statements } else {
12
18/05/2019 Two-Way Decisions A two-way decision is like picking which of two roads to take to the same destination. The fork in the road is the if statement, and the two roads come together just after the false branch.
13
Exact Decimal Arithmetic Problems
18/05/2019 Exact Decimal Arithmetic Problems public class DecimalFraction { public static void main (String[] args) { double x = 1.0; double y = 3.0; if ( x/y == ) { System.out.println("Buy the cookie!" ); } else { System.out.println("No cookie for you."); } Output: ? No cookie for you. The decimal on the right is only an approximation. With more decimal places the approximation gets better, but it is never exactly equal to the fraction. Avoid writing a program that depends on the result of == with decimals.
14
double rounding problems
18/05/2019 double rounding problems double number calculations often have poor accuracy. For the reasons why see the slides of the Conversion presentation. = 0.6 // as expected = // expected to be 0.8!
15
double rounding problems
18/05/2019 double a = 0.7; double b = 0.9; double z = a + 0.1; // = but expected to be 0.8! double y = b - 0.1; // = 0.8 as expected System.out.println(z == y); // false but we would have expected this to be true! double d = 1.0; double e = 0.1; double f = 9 * e; // = 0.9 as expected d = d – f; // = but was expected to be 0.1! double x = ; System.out.println(3.0 == x * (3.0 / x)); // false but this would normally be expected to be always true! // Except for when x = 0 of course, in which case JVM would throw an arithmetic exception (see Data Types & Identifiers/Variables in Java).
16
Conclusion Basically avoid testing for equality using doubles.
18/05/2019 Conclusion Basically avoid testing for equality using doubles. However, your syllabus expects you to be aware of this problem and answer questions regarding it. Possible solutions that are on your syllabus: Round manually. e.g. positive numbers with (int) (x + 0.5), negative numbers with (int) (x - 0.5). See the next slide. Introduce some form of ‘tolerance’. We will go into this in the next presentation.
17
Round manually double a = 0.7; double b = 0.9;
18/05/2019 Round manually double a = 0.7; double b = 0.9; double z = a + 0.1; // = but was expected to be 0.8! double y = b - 0.1; // = 0.8 as expected int c = (int) (z + 0.5); int d = (int) (y + 0.5); System.out.println(c == d); // now true as expected
18
nested if if(condition_1) { Statement1(s); if(condition_2) {
18/05/2019 nested if if(condition_1) { Statement1(s); if(condition_2) { Statement2(s); } An if statement inside another if statement Condition 2 only tested if condition 1 is true Output: ?
19
18/05/2019 if / else if(condition_1) { Statement1(s); if(condition_2) { Statement2(s); } } The statements inside “if” will execute if the condition is true, and the statements inside “else” will execute if the condition is false. Output: ?
20
18/05/2019 if / else if if(condition_1) { /*if condition_1 is true execute this*/ statement(s); } else if(condition_2) { // execute this if condition_1 is not met and condition_2 is met statement(s); } else if(condition_3) { // execute this if condition_1 & condition_2 are not met and condition_3 is met statement(s); } Used when we need to check multiple conditions. Also known as if else if ladder. As soon as the condition is met, the corresponding set of statements get executed, rest gets ignored. If none of the conditions are met then the statements inside “else” gets executed. Flow Chart on next slide.
21
if / else if 18/05/2019 Example on next slide.
Difference between nested ifs & if/else if: Nested if tested ONLY if outer if is true. Else if tested ONLY if initial if and any previous else ifs are false. Difference between multiple ifs & if/else if: Often will give same output but multiple ifs are inefficient if you do not want to test further ifs after one is found true. Multiple ifs would be all be tested regardless of the results of previous ifs. Else ifs are tested ONLY if initial if and any previous else ifs are false. Example on next slide.
22
if / else if 18/05/2019 ? public class IfElseifExample {
public static void main (String args[]){ int num=1234; if (num <100) { System.out .println("Its a two digit number") ; } else if (num <1000) { System.out.println("Its a three digit number"); else if(num <10000) { System.out.println("Its a four digit number") ; System.out.println ("Its a five digit number") ; else { System.out.println ( "number is not between 1 & 99999") ; Output: ?
23
Ending if/else if blocks
18/05/2019 Ending if/else if blocks if/else if blocks of statements that are: Written correctly Written efficiently Anticipate all possibilities Should always end with an else. As there should be only one possibility left. It is considered poor programming style if they don’t. Note: Do not use logical operators (&& ||) for programs in this presentation as these will be covered in the next presentation and are unnecessary (and considered inefficient and poor style) for programs which only test a single variable (which all programs in this presentation will do).
24
18/05/2019 Validation Checks to ensure that the data entered is sensible, reasonable and obeys required rules. e.g. if (ErrorCheck is True) System.out.println(“Suitable Error Message.”) Else { ….. Code that you want executed if everything is OK. …… }
25
? Local Variables Reminder
18/05/2019 Local Variables ? All variables declared inside methods of a class. At the moment we have only looked at the main() method and we will continue to do so for a while, so this will probably not mean much to you at the moment. Therefore, all the variables you will declare up until we start looking at true OOP concepts, will be local ones. All local variables must be given a value at some point during a program otherwise you will receive a “variable might not have been initialized" error – this is probably the most important point at this stage. But also note, just for curiosity: Their scope is limited to their method which means that they can’t be changed or accessed outside of the method. Scope refers to the where a variable can be accessed.
26
"variable might not have been initialized" error
18/05/2019 "variable might not have been initialized" error Some if statements may cause problems and throw this error. e.g. int count = 0; if (length > 0) count = …. ; if (length == 0) count = 0; else count = -1; As even though you might know that length cannot be < 0, JAVAC does not know this and will throw the error above, justifying itself by claiming that if length < 0, count will not have been given a value. Safest solution is initialise all local variables (for now this means all variables you will declare) when you declare them. Another solution is to use else in the example above instead of another if. int count;
27
Commenting on If Statements
18/05/2019 Commenting on If Statements Your comments MUST explain: What are you testing? Why are you testing for this? When (after and before what) are you testing for this and why does it have to be there? What happens if the test is true?
28
Screenshots & Variable names
18/05/2019 Screenshots & Variable names As we are now writing if statements, you will need to give one screenshot per route through your program. It may be possible to show all routes with one screenshot of the console, either way still requires one data entry and output pair per route. You should write the following before each screenshot: Data Entered: …. Expected Output: …. Screenshot: (Should show that what you said was expected actually occurred). All variables should have meaningful names e.g. for a program dealing with marks, you would expect a variable named ‘mark’ (not ‘a’ for example).
29
18/05/2019 Write your own programs: Write your own programs from “scratch”. Of course you should use previous programs for reference, but write your code from “scratch” (do not copy and paste). Note: Do not use logical operators (&& ||) for programs in this presentation as these will be covered in the next presentation and are unnecessary (and considered inefficient and poor style) for programs which only test a single variable (which all programs in this presentation will do).
30
double rounding problems
18/05/2019 Make one of the ways shown below work as expected by rounding (as shown on slide 21). double d = 1.0; double e = 0.1; double f = 9 * e; // = 0.9 as expected d = d – f; // = but was expected to be 0.1! double x = ; System.out.println(3.0 == x * (3.0 / x)); // false but this would normally be expected to be always true! // Except for when x = 0 of course, in which case JVM would throw an arithmetic exception (see Data Types & Identifiers/Variables in Java).
31
Deciding exam grades Specification: 18/05/2019
Set an exam mark from 0 to 100. Display the grade it represents – Merit (60 or more), Pass (40 – 59), Fail (under 40). Do not allow and show suitable error messages if the mark is less than 0 or larger than 100. Create a different error message for each situation: Mark is less than 0. Mark is more than 100. Hint: test for these things first. Note: I do not mean to say that you should code this first when you write your program. I am only referring to the position of the test in your code. You should actually code points 1 & 2 above first (or even just point 1 and the 1st part of point 2). Do not try to code an entire problem at once, break it into pieces. Then code and test each piece before coding the next. This is known as the top-down approach to general problem solving.
32
18/05/2019 Salesman Bonus Write a program for a salesman to set the total value of their sales this year and give their bonus: >= €100,000 then their bonus = €10,000. From €70,000 to €99, then their bonus = €7,000. From €50,000 to €69, then their bonus = €4,000. < then 50,000 then they receive no bonus. Extension: What should be disallowed here? Extend the program to disallow this.
33
System.out.println("Error");
if totalValue < 0 Bonus Program – Very poor Style false elseif totalValue >= false true 1 if / elseif ‘block’ What’s the problem? System.out.println("Error"); There is no need for the final elseif elseif totalValue >= 70000 false true elseif totalValue >= 50000 System.out.println(10000); false true elseif totalValue <= 50000 System.out.println(7000); true System.out.println(4000); true } System.out.println(0);
34
Bonus Program – Very poor Style
if(totalValue<0) System.out.println("Error"); else if(totalValue>=100000) System.out.println("10000"); else if(TotalValue>=70000) System.out.println("7000"); else if(TotalValue>=50000) System.out.println("4000"); else if(TotalValue<50000) System.out.println(“0"); What’s the problem? There is no need for the final elseif
35
System.out.println("Error");
if totalValue < 0 Bonus Program – Better but still poor Style false elseif totalValue >= 1 if / elseif ‘block’ true false System.out.println("Error"); elseif totalValue >= 70000 false true false / else elseif totalValue >= 50000 System.out.println(10000); true System.out.println(7000); true The problem is repeating System.out.println(); What’s the problem? System.out.println(4000); } System.out.println(0); Note: Note: At this stage (before we learn about String variables), this can be acceptable if you are required to print words, like “Merit”, “Pass” etc… in the previous Grade program.
36
Bonus Program – Better but still poor Style if(totalValue<0) System.out.println("Error"); else if(totalValue>=100000) System.out.println("10000"); else if(TotalValue>=70000) System.out.println("7000"); else if(TotalValue>=50000) System.out.println("4000"); else System.out.println(“0"); What’s the problem? The problem is repeating System.out.println();
37
Bonus Program – Improved Style but not working correctly if totalValue
< 0 false elseif totalValue >= true false 1 if / elseif ‘block’ System.out.println("Error"); elseif totalValue >= 70000 false true elseif totalValue >= 50000 false / else bonus = 10000; true What’s the problem? The problem here is that a bonus is printed even if there is an error. bonus = 7000; true bonus = 4000; System.out.println(bonus); bonus = 0; }
38
Bonus Program – Improved Style but
not working correctly if(totalValue<0) System.out.println("Error"); else if(totalValue>=100000) bonus = 10000; else if(TotalValue>=70000) bonus = 7000; else if(TotalValue>=50000) bonus = 4000; else bonus = 0 System.out.println(bonus); What’s the problem? The problem here is that a bonus is printed even if there is an error.
39
Bonus Program – Good Style & Working Correctly if totalValue < 0
false / else nested if / elseif ‘block’ if totalValue >= true false System.out.println("Error"); elseif totalValue >= 70000 false true false / else elseif totalValue >= 50000 bonus = 10000; true bonus = 7000; true bonus = 4000; System.out.println(bonus); bonus = 0; }
40
Bonus Program – Good Style & working correctly
if(totalValue<0) System.out.println("Error"); else { if(totalValue>=100000) bonus = 10000; else if(TotalValue>=70000) bonus = 7000; else if(TotalValue>=50000) bonus = 4000; bonus = 0 System.out.println(bonus); }
41
18/05/2019 Arithmetic Error Write a program that will output the value of the expression: Area /(SpaceWidth * SpaceLength – EmptySpaces) What happens if the following values are used? SpaceWidth ← 7 SpaceLength ← 4 EmptySpaces ← 28 This is called an “arithmetic error”. Add code to stop this situation causing the program to crash. In your comments explain: When (after or before what) did you check for the arithmetic error? Why did you check for it there? What you are checking for? What happens if your check is positive/true?
42
18/05/2019 Happy Or Sad? Using a boolean variable named happy output a suitable message e.g. if true Yippee!!! if false Cheer up!!! Remember that boolean variables can only be true or false and don’t use “” (just the keywords true or false).
43
Check if a number is positive or negative
18/05/2019 Check if a number is positive or negative
44
Check if a number is even or odd
18/05/2019 Check if a number is even or odd
45
Income, Personal Allowance & Tax Rate Extended
18/05/2019 Income, Personal Allowance & Tax Rate Extended Please extend the program above from the previous presentation so that the program gives the right answer if the Salary is less than the Personal Allowance.
46
Melon Packing Plant Extended
18/05/2019 Extend the ”Melon Packing Plant” program written in the previous presentation so that it also calculates: The number of actual boxes needed to pack all the melons (even if one is not full). e.g. 2.5 boxes really means 3 boxes.
47
Cricket Match 18/05/2019 A program is to be written to accept and display the result of a cricket match. The winning team is the one scoring the most runs. The structured English description of the problem is shown here. It assumes the scores are not equal. SET HomeTeamName SET HomeRuns SET AwayTeamName SET AwayRuns SUBTRACT AwaysRuns FROM HomeRuns STORE AS RunDifference CALCULATE the winning team STORE AS WinningTeamName OUTPUT WinningTeamName and RunDifference Typical output is shown. Write this program.
48
5/18/2019 Grade yourself Grade yourself on the vocabulary and learning objectives of the presentation.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.