Understanding Conditional Statements and Control Structures in Java

Slide Note
Embed
Share

Learn about using if and else control structures, boolean variables, and conditional actions in Java programming. Explore examples of making choices and implementing simple comparisons to manage program flow efficiently.


Uploaded on Sep 14, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Making Choices The if Control The else Control Boolean Variables

  2. Overview Having the program choose an action the if control comparing Strings the else control nesting controls combining boolean conditions boolean variables remembering true/false values

  3. Making a Choice Calculating an employee s pay get their hourly pay get how many hours they worked calculate their standard pay if they worked more than 40 hours: add overtime pay issue a cheque for the total pay Sometimes overtime pay is added; sometimes it s not. Depends on how many hours they worked.

  4. Conditional Commands Add overtime pay is conditional computer doesn t always do that worked more than 40 hours is the condition it s either true or false if it s true, then computer adds overtime pay if it s false, the computer doesn t add overtime pay In English/pseudocode: if they worked more than 40 hours, then add overtime pay

  5. The if Control Java syntax: if (condition) { conditionalAction; } note braces go around the command you maybe want to do note indentation: conditional action indented another four spaces! also note: no semi-colon on the if line if they worked over 40 hours is not a command if (hours > 40) { pay = pay + } Remember the Format command in NetBeans! It will do the indentation for you.

  6. if Control Example System.out.print("Hours this week: "); hours = kbd.nextDouble(); kbd.nextLine(); pay = rate * hours; if (hours > 40) { System.out.println("You get overtime pay."); pay = pay + rate * 0.5 * (hours 40); } Condition Conditional Actions Hours this week: 30 Hours this week: 45 You get overtime pay. no overtime pay overtime pay

  7. Simple Comparisons if (hours > 40) if hours is greater than 40 Can also put if in front of these: a == b a is equal to b a != b a is not equal to b a < b a is less than b a <= b a is less than or equal to b a > b a is greater than b a >= b a is greater than or equal to b You can t use the or signs in Java. It doesn t understand them!

  8. Important Difference Checkwhether a is equal to b: a == b two equals signs Make a equal to b: a = b one equals sign Do not get them confused hours == kbd.nextDouble(); not a statement ! if (hours = 40.0) { incompatible types: double cannot be converted to boolean !

  9. Exercises Write if statements: if grade is greater than or equal to 50, print out You passed! if age is less than 18, print out I m sorry, but you re not allowed to see this movie. if guess is equal to secretNumber, print out You guessed it! if y plus 9 is less than or equal to x times 2, set z equal to zero.

  10. Sequential if Controls Each if is separate if (midtermGrade < 50) { System.out.println("You failed the midterm! "); } if (finalGrade < 50) { System.out.println("You failed the final! "); } You failed the midterm! You failed the final! both You failed the midterm! You failed the final! one other neither

  11. Sequential if Controls Each if is separate if (grade < 50) { System.out.println("I m sorry. You failed."); } if (grade > 90) { System.out.println("That is an excellent grade!"); } What grade did you get? 41 I m sorry. You failed. What grade did you get? 95 That is an excellent grade! one other What grade did you get? 75 neither

  12. Sequential if Controls Each if is separate if (grade >= 50) { System.out.println("You passed."); } if (grade < 80) { System.out.println("You didn t get an A."); } What grade did you get? 41 You didn t get an A. What grade did you get? 95 You passed. one other What grade did you get? 75 You passed. You didn t get an A. both

  13. Exercise What is the output of the following code? int age = 24; int height = 180; int weight = 70; int income = 120000; if (age < 18) { if (height > 180) { if (weight <= 50) { if (income >= 100000) { System.out.println("Young!"); } System.out.println("Tall!"); } System.out.println("Thin!"); } System.out.println("Rich!"); }

  14. Making a Choice Taking a lunch order at Greesieberger s ask what sandwich they want add that sandwich to the order ask if they want fries with that if they say yes: add fries to the order ask what drink they want add that drink to the order Sometimes fries are added to the order; sometimes they re not. Depends on what the user wants.

  15. Choosing Fries Ask the user: Do you want fries with that? Get user s answer (should be yes or no) if the answer was yes, add fries to the order In Java (but not right) System.out.print("Do you want fries? "); String answer = kbd.next(); kbd.nextLine(); if ("yes" == answer) Comparing Strings using == or != !

  16. Object Variables Strings are objects == means Are they the very same object? as in My car and my wife s car are the same car want Are they the same value? as in I have the same car as my neighbour My Car My Wife s Car My Neighbour s Car The String in the code What the user typed in "yes" "yes"

  17. Objects and Primitives Strings are objects String name = "Mark"; Scanners are objects, too Scanner kbd = new Scanner(System.in); Data type name starts with a Capital Letter String, Scanner, Car, Color, NOTE: the variable name starts with a small letter name, kbd, Data types without capitals are primitives int, double,

  18. Talking to Objects You can talk to an object: Hey, kbd, give me the next int. kbd.nextInt(); Hey, kbd, give me the next line. kbd.nextLine(); object name, dot, request name, parentheses Also known as calling a method nextInt and nextLine are methods each returns a value that your program can use

  19. Comparing Strings Ask one String about the other String don t use ==, !=, <, <=, >, >= they don t work (or they do the wrong thing) == oneString.equals(anotherString) != ! oneString.equals(anotherString) < oneString.compareTo(anotherString) < 0 <= oneString.compareTo(anotherString) <= 0 > oneString.compareTo(anotherString) > 0 >= oneString.compareTo(anotherString) >= 0 We won t use compareTo very often in CSCI 1226.

  20. String Equality Strings are equal if exactly the same "First String".equals("First String") Any other strings are different! "First String".equals("Second String") "First String".equals("first string") "First String".equals("FirstString") "First String".equals("First String ") Exercise: In each of the false conditions above, what s different between the Strings? true false false false false

  21. Choosing Fries In Java System.out.println("Do you want fries? "); String answer = kbd.next(); kbd.nextLine(); if ("yes".equals(answer)) only accepts yes does not accept Yes , YES , NOTE: We could have asked answer if it was equals to yes : answer.equals("yes") We d get the same answer.

  22. String.equalsIgnoreCase Sometimes don t care if capital or small "First String".equalsIgnoreCase("First String") "First String".equalsIgnoreCase("first string") Any other strings are different! "First String".equalsIgnoreCase("Second String") "First String".equalsIgnoreCase("FirstString") "First String".equalsIgnoreCase("First String ") true true false false false

  23. Choosing Fries In Java System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if ("yes".equalsIgnoreCase(answer)) accepts yes , Yes , YES , (does not accept yeah ) Again, we could have asked answer about yes : answer.equalsIgnoreCase("yes") We d get the same answer.

  24. String.startsWith Accept any answer starting with y as yes System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if (answer.startsWith("y")) Accepts yes , yeah , yup , but not Yes sadly, there is no startsWithIgnoreCase method There s also an endsWith method. And lots of others! Google java string.

  25. String.toUpperCase/toLowerCase Ask a string for upper/lower case version System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); String upperAnswer = answer.toUpperCase(); if (upperAnswer.startsWith("Y")) now accepts Yes , yes , Yeah, yup , upperAnsweris YES , YES , YEAH , YUP answeris still Yes , yes , Yeah , yup

  26. String.oneThing().another() Can combine two steps into one and more, if you want System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if (answer.toUpperCase().startsWith("Y")) if answer is yes , then answer.toUpperCase() is YES , and thatdoes start with a Y This works because answer.toUpperCase() is another String. We can ask anyString a question, even if we haven t given it a name.

  27. Scanner.oneThing().another() Can save the String in upper case to start with and more, if you want System.out.println("Do you want fries?"); String answer = kbd.next().toUpperCase(); kbd.nextLine(); if (answer.startsWith("Y")) change user s answer to upper case before saving it user enters yes ; answer is YES user enters Yup ; answer is YUP This works because kbd.nextLine() is another String. We asked kbd to give us the next line, and it gives us back a String.

  28. Exercise Right now we accept anything that starts with the letter Y (capital or small) if (answer.toUpperCase().startsWith("Y")) accepts You need to speak louder as Yes it starts with the letter Y Change the code so that it only accepts abbreviations of YES as Yes . but still allow capital letters Y, y, YE, ye, YES, yes, Ye, yE, YeS, Yes, HINT: we still need to use startsWith and toUpperCase. But who do we ask, and what do we ask about?

  29. The if-else Control Do exactly one of two things if (grade < 50) { System.out.println("You cannot continue to 1227. "); }else { System.out.println("You can continue to 1227! "); } note the indentation What grade did you get? 41 You cannot continue to 1227. What grade did you get? 95 You can continue to 1227! one other

  30. The if-else Control Java syntax: if (condition) { ifSoAction; } else { otherwiseAction; } Does exactly one of those two things two-way choice do this or do that if is one-way choice do this or not

  31. Better Than Two if Controls Could rewrite if-else into two if controls: if (grade < 50) { System.out.println("You cannot continue to 1227. "); } if(grade >= 50) { System.out.println("You can continue to 1227! "); } but that s error-prone makes it more likely you ll make a mistake

  32. Error-Prone Version What s wrong with this: if (grade < 50) { System.out.println("You cannot continue to 1227. "); } if(grade > 50) { System.out.println("You can continue to 1227! "); }

  33. Error-Prone Version For 1228 you need a 60, so copy the code, change 1227 to 1228, and 50 to 60 if (grade < 60) { System.out.println("You cannot continue to 1228. "); } if(grade >= 50) { System.out.println("You can continue to 1228! "); } what went wrong?

  34. Binary Choices Else is for either-or situations either you pass or you fail no program option for incomplete either you can proceed or you cannot either go left or go right no program option for straight State the condition once Split options between if-body and else-body

  35. Exercise Write if-else controls for if temp is over 30, print Go swimming ; otherwise print Play video games if count is zero, print sum divided by count; otherwise print No numbers entered . if answer starts with a y (or Y), then set price to $10; otherwise set it to $15. if num is even, set it equal to n divided by 2; otherwise set it to n times 3, plus 1 num is even num % 2 == 0

  36. if or if-else? Look at the possible outcomes: outcome #1 computer prints A B C D outcome #2 computer prints A D code: System.out.print("A "); if (something) { System.out.print("B "); System.out.print("C "); } System.out.print("D "); Sometimes prints B and C; Sometimes doesn t: (if control)

  37. if or if-else? Look at the possible outcomes: outcome #1 computer prints A B D outcome #2 computer prints A C D code: System.out.print("A "); if (something) { System.out.print("B "); } else { System.out.print("C "); } System.out.print("D "); Sometimes prints B; Sometimes prints C: (if-else control)

  38. Exercise Possible outcomes: outcome #1: A B C E F outcome #2: A D E F What is the code? Possible outcomes: outcome #1: A B C D outcome #2: A B What is the code?

  39. Exercise Possible outcomes: outcome #1: A B C F G outcome #2: A D E F G outcome #3: A B C F outcome #4: A D E F What is the code?

  40. A Common Mistake Putting braces around everything after if if (thisIsTrue) { doThis(); andThat(); else thisOther(); } 'else' without 'if' ! the else must be after the closing brace of the if otherwise can t find the if it s the else for

  41. if-else inside if-else What time is it? 9 pm Good evening! What time is it? 9 am Good morning! M E Evening: 6pm to 11pm. Morning: 7am to 11am. What time is it? 3 pm Good afternoon! What time is it? 3 am Good grief! A G Afternoon: 12pm to 5pm. 12am to 6 am. pm am

  42. Get the Time // create variables Scanner kbd = new Scanner(System.in); int hour; String amPM; // get the time System.out.println("What time is it?"); hour = kbd.nextInt(); // fix weird clock if (hour == 12) { hour = 0; } // NOTE: read next word in lower case amPM = kbd.next().toLowerCase(); kbd.nextLine(); // read the Enter key!

  43. Print the Message // print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } } else { if ( hour > 6 ) { System.out.println("Good morning!"); } else { System.out.println("Good grief!"); } } A E M G

  44. 9 AM Message // print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } } else { if ( hour > 6 ) { System.out.println("Good morning!"); } else { System.out.println("Good grief!"); } } "am".equals("pm")? NO 9 > 6? YES

  45. Note Indentation 8 12 16 // print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } } else { if ( hour > 6 ) { System.out.println("Good morning!"); } else { System.out.println("Good grief!"); } } Remember the Format command!

  46. if inside if You can put if controls inside if controls if first condition is true, test second condition System.out.println("A"); if (condition1) { System.out.println("B"); if (condition2) { System.out.println("C"); } } A AB ABC possible output: pattern: always A sometimes B when B, sometimes C

  47. Eligible for Pension Who is eligible for a pension seniors (age is 65+) disabled people 55+ who live on their own Only ask question if need to know ask age if 65+ eligible if 55+ and not already eligible ask if disabled if disabled ask if live on own if live on own eligible

  48. Eligible for Pension // ask age System.out.print("How old are you? "); age = kbd.nextInt(); kbd.nextLine(); eligible = (age >= 65); // if 55..64, ask if disabled if (age >= 55 && !eligible) { System.out.print("Are you disabled? "); answer = kbd.nextLine().toLowerCase(); // if disabled, ask if live on own if (answer.startsWith("y")) { System.out.print("Do you live on your own? "); answer = kbd.nextLine().toLowerCase(); eligible = answer.startsWith("y"); } }

  49. Exercise Write nested if/if-else to generate: either "A", "AB", "ABC" or "ABD" either "A", "ABC" or "AC" either "A", "ABC", or "D"

  50. Logical Operators p and q both true (0 < n) && (n < 100) either p or q (or both) are true (m > 0) || (n > 0) p is not true !answer.equals("yes") p && q p || q !p

Related


More Related Content