1 / 154

Decisions, decisions, decisions

Decisions, decisions, decisions. Chapter 5 Spring 2005 CS 101 Aaron Bloomfield. Background. Our problem-solving solutions so far have the straight-line property They execute the same statements for every run of the program public class DisplayForecast // main(): application entry point

Télécharger la présentation

Decisions, decisions, decisions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Decisions, decisions, decisions Chapter 5 Spring 2005 CS 101 Aaron Bloomfield

  2. Background • Our problem-solving solutions so far have the straight-line property • They execute the same statements for every run of the program public class DisplayForecast // main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world"); System.out.print(" market for maybe five "); System.out.println("computers. “); System.out.print(" Thomas Watson, IBM, “); System.out.println("1943.“); } }

  3. Background • For general problem solving we need more capabilities • The ability to control which statements are executed • The ability to control how often a statement is executed • We will concentrate first on controlling which statements are executed • Java provides the if and switch conditional constructs to control whether a statement list is executed • The if constructs use logical expressions to determine their course of action • Examination begins with logical expressions

  4. Logical expressions • The branch of mathematics dealing with logical expressions is Boolean algebra • Developed by the British mathematician George Boole

  5. Logical expressions • A logical expression has either the value logical true or logical false • Some expressions whose values are logical true • The year 2004 is a leap year • A meter equals 100 centimeters • Some expressions whose values are logical false • A triangle has four sides • The area of square is always equal to twice its perimeter

  6. Logical expressions • There are three primary logical operators for manipulating logical values • Logical and • Logical or • Logical not • The operators work as most of us would expect

  7. Quick survey • I’ve seen Boolean logic before… • Lots and lots and lots • A fair amount • Some • Not really

  8. More demotivators

  9. p q p and q False False False False True False True False False True True True Truth tables • We use truth tables to give formal specifications of the operators • “It works as most of us would expect” allows for ambiguity of interpretation • Jim is smiling or Patty is smiling • Can both Jim and Patty both be smiling? • Truth tables • Lists all combinations of operand values and the result of the operation for each combination

  10. p q p or q False False False False True True True False True True True True p not q False True True False Or and not truth tables

  11. p q p and q not (p and q) False False False True False True False True True False False True True True True False Boolean algebra • Can create complex logical expressions by combining simple logical expressions • not (p and q)

  12. (not p) orp q p and q not (p and q) ( not p) (not q) (not q) False False False True True True True False True False True True False True True False False True False True True True True True False False False False DeMorgan’s laws • not (p and q) equals (not p) or (not q)

  13. (not p) andp q p or q not (p or q) ( not p) (not q) (not q) False False False True True True True False True False FalseTrue False False True False False FalseFalse True False True True True False False False False DeMorgan’s laws • not (p or q) equals (not p) and (not q)

  14. DeMorgan’s laws • If you remember nothing else about the Boolean operators, remember that: • not (a and b) == (not a) or (not b) • not (a or b) == (not a) and (not b)

  15. A boolean type • Java has the logical type boolean • Type boolean has two literal constants • true • false • Operators • The and operator is && • Don’t use & • The or operator is || • Don’t use | • The not operator is !

  16. Defining boolean variables • Local boolean variables are uninitialized by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink;

  17. Defining boolean variables • Local boolean variables with initialization boolean canProceed = true; boolean preferCyan = false; boolean completedSecretMission = true;

  18. isWhitespace false receivedAcknowledgement false haveFoundMissingLink false Defining boolean variables • Instance boolean variables are initialized to false by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink;

  19. DeCSS: The program #include<stdlib.h> typedef unsigned int uint; char ctb[512]="33733b2663236b763e7e362b6e2e667bd393db0643034b96de9ed60b4e0e4\ 69b57175f82c787cf125a1a528fca8ac21fd999d10049094190d898d001480840913d7d35246\ d2d65743c7c34256c2c6475dd9dd5044d0d4594dc9cd4054c0c449559195180c989c11058185\ 081c888c011d797df0247074f92da9ad20f4a0a429f53135b86c383cb165e1e568bce8ec61bb\ 3f3bba6e3a3ebf6befeb6abeeaee6fb37773f2267276f723a7a322f6a2a627fb9f9b1a0e9a9e\ 1f0b8f8b0a1e8a8e0f15d1d5584cd8dc5145c1c5485cc8cc415bdfdb5a4edade5f4bcfcb4a5e\ cace4f539793120692961703878302168286071b7f7bfa2e7a7eff2bafab2afeaaae2ff"; typedef unsigned char uchar;uint tb0[11]={5,0,1,2,3,4,0,1,2,3,4};uchar* F=NULL; uint lf0,lf1,out;void ReadKey(uchar* key){int i;char hst[3]; hst[2]=0;if(F==\ NULL){F=malloc(256);for(i=0;i<256;i++){hst[0]=ctb[2*i];hst[1]=ctb[2*i+1];F[i]=\ strtol(hst,NULL,16);}}out=0;lf0=(key[1]<<9)|key[0]|0x100;lf1=(key[4]<<16)|(key\ [3]<<8)|key[2];lf1=((lf1&0xfffff8)<<1)|(lf1&0x7)|0x8;}uchar Cipher(int sw1,\ int sw2){int i,a,b,x=0,y=0;for(i=0;i<8;i++){a=((lf0>>2)^(lf0>>16))&1;b=((lf1\ >>12)^(lf1>>20)^(lf1>>21)^(lf1>>24))&1;lf0=(lf0<<1)|a;lf1=(lf1<<1)|b;x=(x>>1)\ |(a<<7);y=(y>>1)|(b<<7);}x^=sw1;y^=sw2;return out=(out>>8)+x+y;} void \ CSSdescramble(uchar *sec,uchar *key){uint i;uchar *end=sec+0x800;uchar KEY[5]; for(i=0;i<5;i++)KEY[i]=key[i]^sec[0x54+i];ReadKey(KEY);sec+=0x80;while(sec!=\ end)*sec++=F[*sec]^Cipher(255,0);}void CSStitlekey1(uchar *key,uchar *im) {uchar k[5];int i; ReadKey(im);for(i=0;i<5;i++)k[i]=Cipher(0,0);for(i=9;i>=0;\ i--)key[tb0[i+1]]=k[tb0[i+1]]^F[key[tb0[i+1]]]^key[tb0[i]];}void CSStitlekey2\ (uchar *key,uchar *im){uchar k[5];int i;ReadKey(im);for(i=0;i<5;i++)k[i]=\ Cipher(0,255);for(i=9;i>=0;i--)key[tb0[i+1]]=k[tb0[i+1]]^F[key[tb0[i+1]]]^key\ [tb0[i]];}void CSSdecrypttitlekey(uchar *tkey,uchar *dkey){int i;uchar im1[6]; uchar im2[6]={0x51,0x67,0x67,0xc5,0xe0,0x00};for(i=0;i<6;i++)im1[i]=dkey[i]; CSStitlekey1(im1,im2);CSStitlekey2(tkey,im1);}

  20. DeCSS: The shirt (and tie!)

  21. DeCSS: The poem How to decrypt a DVD: in haiku form. (Thanks, Prof. D. S. T.) ------------------------ (I abandon my exclusive rights to make or perform copies of this work, U. S. Code Title Seventeen, section One Hundred and Six.) Muse! When we learned to count, little did we know all the things we could do some day by shuffling those numbers: Pythagoras said "All is number" long before he saw computers and their effects, or what they could do Table Zero is: Five, zero, one, two, three, four, oh, one, two, three, four. Table One is long: two to the eighth power bytes. Ready? Here they are: Fifty one; then one hundred fifteen; fifty nine; thirty eight; ninety nine; thirty five; one hundred seven; one hundred eighteen; sixty two; one hundred twenty six; fifty four; forty three; one hundred ten; then

  22. DeCSS: The number • The world’s first illegal prime number: 485650789657397829309841894694286137707442087351357924019652073668698513401047237446968797439926117510973777701027447528049058831384037549709987909653955227011712157025974666993240226834596619606034851742497735846851885567457025712547499964821941846557100841190862597169479707991520048667099759235960613207259737979936188606316914473588300245336972781813914797955513399949394882899846917836100182597890103160196183503434489568705384520853804584241565482488933380474758711283395989685223254460840897111977127694120795862440547161321005006459820176961771809478113622002723448272249323259547234688002927776497906148129840428345720146348968547169082354737835661972186224969431622716663939055430241564732924855248991225739466548627140482117138124388217717602984125524464744505583462814488335631902725319590439283873764073916891257924055015620889787163375999107887084908159097548019285768451988596305323823490558092032999603234471140776019847163531161713078576084862236370283570104961259568184678596533310077017991614674472549272833486916000647585917462781212690073518309241530106302893295665843662000800476778967984382090797619859493646309380586336721469695975027968771205724996666980561453382074120315933770309949152746918356593762102220068126798273445760938020304479122774980917955938387121000588766689258448700470772552497060444652127130404321182610103591186476662963858495087448497373476861420880529443

  23. DeCSS: The images

  24. DeCSS: The recordings • All this info from http://www-2.cs.cmu.edu/~dst/DeCSS/Gallery/ • Or do a Google search for “decss gallery”

  25. DeCSS: The movie

  26. Other operators • Equality operators == and != • Operator == • Returns true if the operands have the same value; otherwise, returns false • This is not the assignment operator! • Operator != • Returns true if the operands have different values; otherwise, returns false • The operators work with all types of values

  27. Evaluating boolean expressions • Suppose boolean p = true; boolean q = false; boolean r = true; boolean s = false; • What is the value of p p && s !s p == q q q != r p && r r == s q || s q != s

  28. Evaluating boolean expressions • Suppose int i = 1; int j = 2; int k = 2; char c = '#'; char d = '%'; char e = '#'; • What is the value of j == ki != k i == jj != k c == ed != e c == d c != e

  29. Floating point precission • What gets printed? class FloatTest { public static void main (String args[]) { double y = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1; System.out.println (y); } } • FloatTest.java There are 10 0.1’s

  30. Take care with floating-point values • Consider double a = 1; double b = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 double c = .9999999999999999; • Two true expressions! c == b b != a • Two false expressions! a == b b != c • Problem lies with the finite precision of the floating-point types • Instead with the ordering operators for closeness

  31. How to solve this • Don’t compare floating-point values if you can help it! • Both doubles and floats • Need to test if the two doubles are “close” in value final double EPSILON = 0.000001; boolean foo = Math.abs (a-b) < EPSILON;

  32. Ordering operators • Java provides ordering operators for the primitive types • Four ordering operators, <, >, <=, and >= • They correspond to mathematical operators of <. >, ≤, and ≥ • Together the equality and ordering operators are known as the relational operators • False is less than true

  33. Evaluation boolean expressions • Suppose int i = 1; int j = 2; int k = 2; • What is the value of i < j j < k i <= k j >= k i >= k

  34. Unicode values • Character comparisons are based on their Unicode values • Characters ‘0’, ‘1’, … ‘9’ have expected order • Character ‘0’ has the encoding 48 • Character ‘1’ has the encoding 49, and so on. • Upper case Latin letters ‘A’, ‘B’, … ‘Z’ have expected order • Character ‘A’ has the encoding 65, character ‘B’ has the encoding 66, and so on. • Lower case Latin letters ‘a’, ‘b’, … ‘z’ have expected order • Character ‘a’ has the encoding 97 • Character ‘b’ has the encoding 98, and so on.

  35. Evaluation boolean expressions • Suppose char c = '2'; char d = '3'; char e = '2'; • What is the value of c < d c < e c <= e d >= e c >= e

  36. Operator precedence revisited • Highest to lowest • Parentheses • Unary operators • Multiplicative operators • Additive operators • Relational ordering • Relational equality • Logical and • Logical or • Assignment

  37. Expressions vs. statements • A statement is a single command for Java to do, and always ends in a semi-colon (for now, at least) • System.out.println (“hello world”); • int x = 4; • ++x; • An expression returns a value, and does not have a semi-colon • 5 • circle.getRadius() • x • Note the difference between the following: • ++i is an expression • ++i; is a statement

  38. Quick survey • I felt I understood expressions • Very well • With some review, I’ll be good • Not really • Not at all

  39. A bit of humor…

  40. Conditional constructs • Provide • Ability to control whether a statement list is executed • Two constructs • If statement • if • if-else • if-else-if • Switch statement

  41. Expression true false Action Basic if statement • Syntax if (Expression) Action • If the Expression is true then execute Action • Action is either a single statement or a group of statements within braces • For us, it will always be a group of statements within braces

  42. Is our number negative? If Value is less than Value < 0 zero then we need to update its value true false to that of its additive If Value is not inverse less than zero then our number Value = -Value is fine as is Our number is now definitely nonnegative Example if (value < 0) { value = -value; }

  43. Sorting two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); // rearrange numbers if necessary if (value2 < value1) { // values are not in sorted order int rememberValue1 = value1; value1 = value2; value2 = rememberValue1; } // display values System.out.println("The numbers in sorted order are " + value1 + " and then " + value2); What happens if the user enters 11 and 28? What happens if the user enters 11 and 4?

  44. Are the numbers out of order Rearrange value1 and value2 < value1 value2 to put their values in the proper order false true int rememberValue1 = value1 value1 = value2 value2 = rememberValue1 The numbers were rearranged into the proper order The numbers were initially in order The numbers are in order If semantics

  45. What an if statement executes • An if statement executes the next block of code • A block is either: • A single statement without curly brackets: if (a == b) System.out.println (“a==b!!!”); • A number of statements enclosed by curly brackets: if (a == b) { System.out.print (“a”); System.out.print (“==”); System.out.print (“b”); System.out.println (“!!!”); }

  46. Why we always use braces • What is the output? int m = 5; int n = 10; if (m < n) ++m; ++n; System.out.println(" m = " + m + " n = " n);

  47. Quick survey • I felt I understood the if statement • Very well • With some review, I’ll be good • Not really • Not at all

  48. Today’s demotivators

  49. Expression false true Action1 Action2 The if-else statement • Syntax if(Expression) Action1elseAction2 • If Expression is true then execute Action1otherwise execute Action2 • The actions are either a single statement or a list of statements within braces

  50. Finding the maximum of two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt();System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); int maximum; if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger } else { // (value1 >= value2) maximum = value1; // no: value2 is not larger } System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum); But is it initialized?

More Related