documentz
TRANSCRIPT
Chapter 4: Introduction to control statements!• Additional operators!
• a += 3;! ! ! //Equivalent to a = a + 3; !• a -= 3;! ! ! //Equivalent to a = a - 3; !• a /= 3;! ! ! //Equivalent to a = a / 3; !• a *= 3;! ! ! //Equivalent to a = a * 3; !• a %= 3;! ! ! //Equivalent to a = a % 3; !• a += "foo";! ! //Equivalent to a = a + "foo"; !• a++;! ! ! //Equivalent to a = a + 1;!• a—;! ! ! //Equivalent to a = a - 1;!
• Standard classes and methods!• You can use these in java without importing them!
• Usage: !• double area = 10.0, radius; //important, go over that this creates a double named radius!• radius = Math.sqrt(area / Math.PI)!
• Random class methods!
• If statements!if (condition returns true) {! //if this is true ! statement;! ! //execute this statement!! statement;! ! //and then this statement} ! ! ! ! //Whitespace doesn’t matter with if / else statements!else {! ! ! ! //if condition does not return true!! statement;! ! //execute this statement!}!• Additional forms!
• Braces can be dropped if only a single statement follows the word if or else; for instance!!!
if (condition) //note that statements with / without brackets can be mixed and matched!! statement;!else !! statement;!!• Boolean expressions: Either returns the value true or false (alternatively 1 and 0,
respectively) !• Conditions in if / else statements must be a boolean expression!• Note that relational operations like (x > y) return either true or false!
• Relational operators: return true or false !
• Examples of operators / usage / bad usage!
• Common use: Check for validity of input!• While statement: Execute statements while a statement is true !
• Usage: !int x = 0;!while (x < 3) { //the x is a counter, thus thus is a Count controlled loop!! System.out.println(x);!! x++;!}!output:!0!1!2!!Exercise: make a flowchart for a while statement!!Entry controlled loop: for loops and while loops, as the condition is tested at the beginning of each iteration!!For loops: “count controlled input” !for (int i = 0; i <= 3; i++) { //while i<=10 do the following. i++ is what happens to the variable every iteration. int i = 0 is what happens during initialization ! System.out.println(i); }!!output:!0!1!2!!• Nested control statements!
• You can combine everything together to make more complex programs!• You can also nest if loops etc:!
• if x -> check if y -> do something if y / do something if not y!• Break statement:!
• use the statement “break” to end a for loop or a while loop!• Sentinel controlled input: when you put an if statement that leads to a break
inside a loop!• Potential errors:!
• You could do int i = 0 in a for loop when another for loop is already using i (if its nested) or if its already initialized !
• You could forget to initialize the integer that you’re iterating with !• Floating point precision: 1 for a float is actually .99999999999999 because of
binary arithmetic and decimal representations.