270 likes | 281 Views
This lecture covers system input, Boolean expressions, operators, control statements, and programming style in Java. Topics include system input methods, conditional and iterative statements, and the importance of proper programming style in writing code.
E N D
Lec.3Statement and Control Flows: Jiang (Jen) ZHENG May 16th, 2005
Outline • System Input: tio package • Introduction to Statements • Boolean Expressions • Relational and Equality Operators • Logical Operators • Precedence, associativity and laws in boolean algebra • Conditional Statement • if, if-else statement • Iterative statement • while loop statement • for loop statement • break, continue statement • switch statement • Programming style in this chapter CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
System Input: tio packet • Can be downloaded/copied from/afs/cs.pitt.edu/user0/jzheng/public/html/CS401/Codes/tio/* • To use tio package: • Compile the whole package • import tio.*; • int a = Console.in.readInt(); --- read in an integer • char a = Console.in.readChar (); --- read in a char • double a = Console.in.readDouble (); --- read in a double • float a = Console.in.readFloat (); --- read in a float • long a = Console.in.readLong (); --- read in a long • String a = Console.in.readWord(); --- read in a word • String a = Console.in.readWord(); --- read in a whole line CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Program Sequence Linear Execution Conditional Execution Iterative Execution if, if-else switch statements while, for statements CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Introduction to Statements • Units of declaration or execution • A program execution can be broken down into execution of the program’s individual statements • Every Java statement must be terminated by a semicolon(;) • Variable declaration statements • type variableIdentifier[s]; Ex: double size=1.5, x; • Expression statements • Assignment expressionEx: area= width*height; • Method call expressionEx: System.out.println(…); CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Introduction to Statements (Cont.) • Block: a grouping of a number of statements enclosed by braces. Can be nested blocks. • Empty Statement • ; (no action) { x = 1; { int y = 2; System.out.println(y); } ;;;; System.out.println(x); } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Boolean Expressions • Boolean primitive type: true, false • Result from expressions involving either relational operators or logical operators • Relational and equality operators • <, >, ==, <=, >=, != • Ex: 10 == 20 is false; 10 <= 10 is true • Compare: == (equality operator) and = (assignment operator) CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
A B !A A&&B A||B true true false true true true false false false true false true true false true false false true false false Boolean Expressions • Logical Operators • &&, ||, ! • Ex: (x=10, y=20) (x<20) && (y<30) is true • Truth Table of the logical operators CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Operator Associativity ( ) ++(postfix) --(postfix) Left to right +(unary) -(unary) ++(prefix) --(prefix) ! Right to left new (type)expr Right to left * / % Left to right + - Left to right < <= > >= Left to right == != Left to right && Left to right || Left to right = += -= *= /= %= etc. Right to left ( (i < j ) || ( (j < k) && (x <= y) ) ) ( i / 3 ) = = y ( x / 3 ) = = y ! ( x != i ) Operator Precedence and Associativity • Some Examples: int i=10, j=15, k=20;double x=10.0, y=3.333333; i < j || j < k && x <= y true (i / 3 ) = = y false (x / 3 ) = = y false CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3 ! ( x != i ) true
The Laws of Boolean Algebra • Commutative law: a or b == b or a; a and b == b and a • Distributive and law: a and ( b or c) == (a and b) or ( a and c) • Distributive or law: a or ( b and c) == (a or b) and ( a or c) • Double negation: !!a == a • DeMorgan’s Law: !(a or b) == !a and !b !(a and b) == !a or !b CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Control Statement • Conditional execution • Statements may or may not execute • Iterative execution • Statements may execute more than one time Conditional Execution Iterative Execution while, for statements if, if-else switch statements CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The if Statement • General Forms: or • <true option> and <false option> can be any Java statement or a block. • The parenthesis around the boolean expression is required • if ( BooleanExpression ) • < true option > • else • < false option > • if ( BooleanExpression ) • < true option > CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Nested if statement Both of the <true option> and <false option> can by any Java statement. If they are if statement, we get the nested if statements. An else will be associated with the “closest”, unassociated, non-terminated if statement. CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Nested if statement Example: if (grade >= 95) if ( extraCredit ) System.out.println (“A+”); else System.out.println (“?”); • Which does this <false option> associated with? • The condition-2 • There will be no problem for the computer but may lead the programmer for a LOGIC ERROR. • Logic Error: the program can compile and it may run and seem fine, but the result is incorrect because of this logic error. • How to prevent this kind of error? • Using blocks ( braces) CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
More Conditional Statement Examples (I) if ( x < y ) ; System.out.println (“The smaller is ” + x ); else; System.out.println (“The smaller is “ + y); Compile Error if ( x < y ) ; System.out.println (“The smaller is ” + x ); System.out.println (“The smaller is “ + y); Given x = 3 and y = 4 • What will be printed out? • The extra semicolons cause the <true option> to be empty statements. The smaller is 3 The smaller is 4 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
More Conditional Statement Examples (II) if (temperature < 32 ) System.out.println (“It is now “); System.out.print (temperature - 32); System.out.println ( “ below freezing.” ); System.out.println (“It’s ” + temperature + “degrees”); Given temperature = 45 13 below breezing. It’s 45 degrees • What will be printed out? • How to prevent this unpredicted behavior? Using blocks. if (temperature < 32 ) { System.out.println (“It is now “); System.out.print (temperature - 32); System.out.println ( “ below freezing.” ); } System.out.println (“It’s ” + temperature + “degrees”); CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
More Conditional Statement Examples (III) if ( 18 <= age < 65 ) … • Using the precedence and associativity property of <= and <, it will be evaluated as • (18 <= age) will return true or false. • true/false < 65 will cause error because the relational operators are used to compare two numbers. • Good thing: Compiler can catch it! • To fix it: Using logical operator ( ( 18 <= age ) < 65 ) if ( (18 <= age) && ( age < 65) ) CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The while Statement • General Forms: • Flow Chart: • The <loop body> can be any Java Statement. • while ( BooleanExpression ) • <loop body> True BooleanExp • Statement False CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
ForInit True • UpdateExpr BooleanExp • Statement False The for Statement • General Forms: • Flow Chart: • Is Equivalent to: • for ( ForInit; BooleanExpression; UpdateExpr ) • <loop body> • ForInit; • while ( BooleanExpression ) { • <loop body> • UpdateExpr; • } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The for Statement Examples • Usually used as a counting loop. • For example: • ForInit: i = 1; • UpdateExpr: i++; • BooleanExpr: i<=100; • Loop Body: sum += i; • for ( i=1; i<=100; i++ ) • sum += i; CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The break and continueStatements • They both interrupt the normal flow of control. • break: • Cause an exit from the innermost enclosing loop. • Cause switch statement to terminate. • continue: • Cause the current iteration of a loop to stop and cause the next iteration of a loop to begin immediately CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The break and continue examples import tio.*; class BreakContinue { public static void main( String[] args ) { int n; while (true) { System.out.print (“Enter a positive integer or 0 to exit”); n = Console.in.readInt(); if ( n==0 ) break; if ( n <0 ) Continue; System.out.print (“Square root of ” + n + “ = ” + Math.sqrt(n) ); } System.out.println (“Break land here: a zero is entered.”); } } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The switch statement • switch statement can be used when choices are simple, integer values. • General Format: • switch ( int_expr ) { • case constant_expr: • … • case constant_expr: • … • default: // This is optional • } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The effect of switch statement • Evaluate the init_expr expression • Go to the case label having a constant value that matches the value of the expression found in step 1; or, if a match is not found, go to the default label; or if there is no default label, terminate switch. • Continue executing statements in order until the end of switch is reached or a break is encountered. • Terminate switch when a break statement is encountered, or terminate switch by “falling off the end” CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
The switch statement Example • if ( dayOfWeek == 1 ) { • print (“Sunday”); • } else if ( dayOfWeek == 2 ) { • print (“Monday”); • } else if ( dayOfWeek == 3 ) { • print (“Tuesday”); • } else if ( dayOfWeek == 4 ) { • print (“Wednesday”); • } else if ( dayOfWeek == 5 ) { • print (“Thursday”); • } else if ( dayOfWeek == 6 ) { • print (“Friday”); • } else if ( dayOfWeek == 7 ) { • print (“Saturday”); • } else { • print (“Not a day number”); • } • switch ( dayOfWeek ) { • case 1: • print (“Sunday”); • break; case 2: • print (“Monday”); • break; • case 3: • print (“Tuesday”); • break; • … • default: • print (“Not a day number”); • } • public void print (String s) { • System.out.println (s); • } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Programming Style Acceptable Style1: if ( x > y ) { System.out.println (“x is larger ” + x); max = x; } While ( i < 10 ) { sum = sum + i; i ++; } Acceptable Style1: • Opening or left brace stays on the same line. • The Closing or right brace lines up under the keyword that starts the overall statement. Acceptable Style 2: if ( x > y ) { System.out.println (“x is larger ” + x); max = x; } Acceptable Style 2: Each brace is kept on a separate line. CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3
Topics for next lecture • Reading Assignment: Chapter 4 You don’t need to know the details but you should know what are those when I talk about it. CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 3