Presentation is loading. Please wait.

Presentation is loading. Please wait.

Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)

Similar presentations


Presentation on theme: "Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)"— Presentation transcript:

1 Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)

2 Program Flow  Sequence: do commands in order  the “normal” order  Selection: skip over some commands  “if”, “if-else”, and “switch” controls  Repetition: do some commands over again  “while”, “for” and “do-while” controls

3 Yes or Whatever!  Recall “Do you want fries with that?”  accepts “yes” in any case »“yes”, “YES”, “Yes”, …  if (resp.equalsIgnoreCase("Yes")) { order.add("fries"); }  …treated anything else as no »“sure”, “yeah”, “yup”, “yes, please”, …

4 What Do We Want?  Ideally?  Anything that means yes  yes  Anything that means no  no  Anything else  try again  That’s too hard! How about  Yes  yes  No  no  Anything else  try again

5 Getting a Yes/No Answer System.out.print(“Do you want fries with that? ”); String resp = kbd.next(); kbd.nextLine(); if (resp.equalsIgnoreCase(“yes”)) { order.add(“fries”); order.add(“fries”);}  Want them to answer “yes” or “no”  So if they give a different answer?  Ask them again

6 Asking Again  First answer is wrong  ask them again  Right first time  doesn’t ask again Do you want fries with that? Do you want fries with that? yup Please say yes or no: Please say yes or no: yes Do you want fries with that? Do you want fries with that? sure Please say yes or no: Please say yes or no: yes Do you want fries with that? Do you want fries with that? nope Please say yes or no: Please say yes or no: no Do you want fries with that? Do you want fries with that? yes ABAB ABAB ABAB A do the A step; possibly do the B step

7 Asking Again // A – done first System.out.print(“Do you want fries with that? ”); resp = kbd.next(); kbd.nextLine(); if (!resp.equalsIgnoreCase(“yes”) // not yes && !resp.equalsIgnoreCase(“no”)) {// and not no // B – possibly done // B – possibly done System.out.print(“Please say yes or no: ”); System.out.print(“Please say yes or no: ”); resp = kbd.next(); kbd.nextLine(); resp = kbd.next(); kbd.nextLine();} if (resp.equalsIgnoreCase(“yes”)) { order.add(“fries”); order.add(“fries”);}

8 Asking Again Again  Second answer is wrong  ???  uses that wrong answer »which is not equalsIgnoreCase(“yes”), so  no!  Maybe it should ask again again Do you want fries with that? Do you want fries with that? yup. Please say yes or no: Please say yes or no: yes, please. Do you want fries with that? Do you want fries with that? yup. Please say yes or no: Please say yes or no: yes, please. Please say yes or no: Please say yes or no: I did! Please say yes or no: Please say yes or no: yes ABAB ABBBABBB do the A step; as necessary do the B step

9 Getting a Yes/No Answer // A – done first System.out.print(“Do you want fries with that? ”); resp = kbd.next(); kbd.nextLine(); while (!resp.equalsIgnoreCase(“yes”) // not yes && !resp.equalsIgnoreCase(“no”)) {// and not no // B – possibly repeated // B – possibly repeated System.out.print(“Please say yes or no: ”); System.out.print(“Please say yes or no: ”); resp = kbd.next(); kbd.nextLine(); resp = kbd.next(); kbd.nextLine();} if (resp.equalsIgnoreCase(“yes”)) { order.add(“fries”); order.add(“fries”);} Just change the “if” to “while”

10 The “while” Control  Java Syntax  while (condition) { repeatedAction(s); }  if the condition is true, do the repeated action, and keep doing the repeated action until the condition becomes false »if condition starts out false, body gets skipped

11 Note: No “else” for “while”  You can change an if to a while  if the data is bad, ask again  if the data is still bad, ask again  …  You can’t change an if-else to a while  if the data is bad, ask again, otherwise use it  if the data’s still bad, ask again, otherwise use it  just do the “use it” part after the loop

12 Exercise: Getting a Valid Grade What did you get on the test? What did you get on the test? 1000 Grade must be 0 to 100: Grade must be 0 to 100: 999 Grade must be 0 to 100: Grade must be 0 to 100: 9998 Grade must be 0 to 100: Grade must be 0 to 100: 98 What did you get on the test? What did you get on the test? 100 What did you get on the test? What did you get on the test? 0 What did you get on the test? What did you get on the test? -10 Grade must be 0 to 100: Grade must be 0 to 100: 100 do the A step; as necessary do the B step ABBBABBB ABAB A A

13 Things to Notice  In both examples:  needed to get first answer before the loop (I call this the loop initialization)  test was that the input is not what we’re looking for (“bad” input)  last command in loop is to get new input (I call this loop update)  it’s the same variable in initialization, test and update (I call it the loop control variable)

14 Parts of a (while) Loop System.out.print(“You have a disability? ”); resp = kbd.next(); kbd.nextLine(); Initialization Happens before the “while” command Gets the first data value (Example: the user’s first answer to the question) loop control variable: resp

15 Parts of a (while) Loop while (!resp.equalsIgnoreCase(“YES”) && !resp.equalsIgnoreCase(“NO”)) { && !resp.equalsIgnoreCase(“NO”)) { Test In parentheses after the “while” Is the test to keep going Is opposite of when to stop (Example: Stop when is resp is YES or NO; i.e. Keep going if resp is not YES and it’s not NO) loop control variable: resp

16 Parts of a (while) Loop System.out.print(“Yes or no? ”); System.out.print(“Yes or no? ”); Process This is the thing we want to do to each data value (Example: Tell user what we’re looking for.)

17 Parts of a (while) Loop resp = kbd.next(); kbd.nextLine(); resp = kbd.next(); kbd.nextLine(); Update Last thing to do in the loop!!! Get the next data value (Example: the user’s next response) loop control variable: resp

18 Initialization & Update System.out.print(“You have a disability? ”); resp = kbd.next(); kbd.nextLine(); resp = kbd.next(); kbd.nextLine(); resp = kbd.next(); kbd.nextLine(); Usually the Same Especially if it’s an input command. (There are often slight variations.) loop control variable: resp

19 Loop Execution  Initialization is carried out  Loop condition is tested  if test passed » Body is executed » Update command is executed » Goes back to loop condition  Continues until test fails  “termination condition”

20 On the Importance of Updates  It’s important that you do it! Sop("…isability?"); r = kbd.next(); while (!r.equals("yes") && !r.equals("no")) { Sop("Yes or no? "); } You have a disability? yup Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no? Yes or no?

21 On the Importance of Updates  It’s important that you do it last! Sop("…isability? "); r = kbd.next(); while (!r.equals("yes") && !r.equals(“no”)) { r = kbd.next(); Sop("Yes or no? "); } You have a disability? yup hello? Yes or no? what? Yes or no? yes Yes or no? People with disabilities should contact the department of social services at the address below.

22 Not Just for Bad Input  Can use while loops for good data, too  recall JavaAverage  bad input  loop ends Enter a number: 10 Enter another number or -1 to quit: 20 Enter another number or -1 to quit: 30 Enter another number or -1 to quit: 40 Enter another number or -1 to quit: -1 The average of the positive numbers you entered is 25.0. ABBBBCDABBBBCD

23 Exercise: Loop Control  Write the loop control for that loop  don’t worry about finding the average! Enter a number: 10 Enter another number or -1 to quit: 20 Enter another number or -1 to quit: 30 Enter another number or -1 to quit: 40 Enter another number or -1 to quit: -1 Oops! I forgot to find the average! ABBBBCDABBBBCD

24 Loop Processing  Extra stuff that needs doing inside loop  For each of the numbers, we must... ...add it to a running sum, and... ...count it  Remember: inside the loop, you only have one piece of data  add it to the running sum (not them)  count it (not them)

25 Adding and Assigning  Recall that we use + to add, = to assign totalTax = provTax + fedTax;  provTax + fedtax just adds the numbers  totalTax = saves the answer  We can put the two steps together sum += num;  +=  add and assign  add these numbers together and save the answer »saved in the variable on the left »so same as sum = sum + (num);

26 Special Assignment Operators  Works for all the math operators  var += expradd expr to var  var - = exprsubtract expr from var  var * = exprmultiply var by expr  var / = exprdivide var by expr  var % = expr(exercise) »var must be a variable »expr can be an expression courseGrade += LAB_WEIGHT * labPercent;

27 Counting  Adding one to a variable is very common  that’s what counting is!  Could use += to add one... count += 1; ...but that’s five keystrokes  We can do it in two count++;  ++  add one to this variable  called “increment”

28 Increment & Decrement  These operations that are common in loops  var++add one to var  ++varadd one to var  var--subtract one from var  --varsubtract one from var  You will see both prefix & suffix versions  they are slightly different  the difference doesn’t matter to us

29 JavaAverage Review int sum, count, num; double ave; sum = 0; count = 0; num = kbd.nextInt(); kbd.nextLine(); // LCV init. while (num >= 0) { // LCV test. sum += num; // add num to sum sum += num; // add num to sum count++; // count num count++; // count num num = kbd.nextInt(); kbd.nextLine(); // LCV upd. num = kbd.nextInt(); kbd.nextLine(); // LCV upd.} ave = (double)sum / (double)count; Needs S.o.p commands!

30 Exercise  Track the variables’ values abc a = 1;1?? a++; b = a + 6; b--; c = b * 5; c += a; a *= 10; b /= 2; c %= 4; a *= b + c;  note: sums b and c before it multiplies

31 Definite or Indefinite  Repeat unknown number of times  ABBBBBBCD, ABBBBCD, ACD, ABCD,...  “indefinite iteration” or “data controlled loop”  usually a while loop  Repeat known number of times  ABBBC, ABBBC, ABBBC, ABBBC,...  “definite iteration” or “count controlled loop”  can be done with a while loop »but we have a better way!

32 Count-Controlled  It’s not the data that tells us to stop  just count how many times it’s done Enter your A1 grade: 100 Enter your A2 grade: 98 Enter your A3 grade: 87 Enter your A4 grade: 99 Enter your A5 grade: 100 Enter your A6 grade: 80 Your average is 94.0. AAAAAABCAAAAAABC loop control variable: the assignment number!

33 Count-Controlled while Loop int sum, asgn, grade; double ave; sum = 0; asgn = 1; // LCV initialized while (asgn <= 6) { // LCV tested grade = kbd.nextInt(); kbd.nextLine(); grade = kbd.nextInt(); kbd.nextLine(); sum += grade; sum += grade; asgn++; // LCV updated asgn++; // LCV updated} ave = (double)sum / 6; Needs S.o.p commands! Question: why not divide by asgn instead of 6? Question: why (double)sum?

34 Dividing Integers & Doubles  Java uses / for both int and double division  15 / 2 is 7because 15 and 2 are both int  15.0 / 2.0 is 7.5because 15.0 & 2.0 are doubles  “Mixed” expressions use double division  15.0 / 2 is 7.5; 15 / 2.0 is 7.5  (double) says use the double version of this  (double)15 / 2 is 7.5; 15 / (double)2 is 7.5  If sum is 17, then (double)sum is 17.0  but sum is still an int (17);it doesn’t change!

35 Changing doubles to ints  Can also change the other way  use (int) in front of a double value/variable double price = 15.99; int dollars = (int)price; int cents = (int)(100 * (price – dollars)); System.out.println(dollars + " dollars and " + cents + " cents.");  NOTE: it doesn’t round off; it truncates! 15 dollars and 99 cents. To Round off, use: int approxDollars = (int)Math.round(price);

36 Switching int/double and String  Can’t say (String)42 or (int)"42"  not quite that easy to make those changes  Can do conversions using special methods: Integer.toString(42)Double.toString(42.6)Integer.parseInt("42")Double.parseDouble("42.6") »of course you’d usually use variables inside the ()s »and you don’t usually need to convert #s to Strings Integer and Double are special classes; toString, parseInt and parseDouble are methods.

37 The for Control  Count-controlled loops very common  Want a shorter/easier way to make them  All loop control actions in one place  initialization (usually = 1)  test (usually <= something)  update (usually ++)  The “for” loop control

38 Count-Controlled for Loop int sum, asgn, grade; double ave; sum = 0; for (asgn = 1; asgn <= 6; asgn++) { // LCV i/t/u grade = kbd.nextInt(); kbd.nextLine(); grade = kbd.nextInt(); kbd.nextLine(); sum += grade; sum += grade;} ave = (double)sum / 6; Needs S.o.p commands!

39 Easy Mistake to Make  Change number of assignments to 10 int sum, asgn, grade; double ave; sum = 0; for (asgn = 1; asgn <= 10; asgn++) { grade = kbd.nextInt(); kbd.nextLine(); grade = kbd.nextInt(); kbd.nextLine(); sum += grade; sum += grade;} ave = (double)sum / 6; What went wrong? How can we prevent that kind of mistake?

40 Constants  Literals  numbers: 3, 22, 3.14159  characters: ‘a’, ‘A’, ‘&’  strings: “Hello, world!”  Named / Symbolic constant  identifier  must be declared public static final int NUM_ASGN = 6;

41 Constants  Constant declarations go inside the class  but not inside the method(s) public class CircleCalculation { public static final int NUM_ASGN = 6; public static void main(String[] args) { …}}

42 Why Named Constants  Easier to read and understand  Changing value easier  one change instead of many  coincidental equality is not a problem »is this 100 the max grade or the max enrolment?  Compiler can catch the mistake  Typo: 3.14519 for 3.14159 computer: “OK.”  Typo: NUM_AGSN for NUM_ASGN computer: “Huh?”

43 Naming Styles  Use meaningful names  Use multiple words as appropriate  Naming conventions  variableName  CONSTANT_NAME

44 Exercise  Declare Java constants for  the maximum allowable enrolment for a course (which is 100)  the number of feet in a mile (5280)  the number of cm in an inch (2.54)  the name of a data file (numbers.txt)

45 Loop using Constant public static final int NUM_ASGN = 6; public static void main(String[] args) { int sum, asgn, grade; int sum, asgn, grade; double ave; double ave; sum = 0; sum = 0; for (asgn = 1; asgn <= NUM_ASGN; asgn++) { for (asgn = 1; asgn <= NUM_ASGN; asgn++) { grade = kbd.nextInt(); kbd.nextLine(); grade = kbd.nextInt(); kbd.nextLine(); sum += grade; sum += grade; } ave = (double)sum / NUM_ASGN; ave = (double)sum / NUM_ASGN;} Still needs S.o.plns! Exercise: change the number of assignments to 10.

46 while vs. for  Same four parts of loop  Initialization, test, processing, update  while loops & for loops do exactly the same for (initialize; test; update) { process; } initialize; while (test) { process; update; }

47 Count Controlled Loops  The “for” control is used when you know ahead of time how many iterations you want  we wanted six assignment grades: six iterations  count the iterations: count controlled loop  In general, NUM_ITERATIONS iterations for (iter = 1; iter <= NUM_ITERATIONS; iter++) { (loop body = actions to be repeated) } iter is the loop control variable; NUM_ITERATIONS is how many iterations we want.

48 Exercises  Write a loop to print out “Hello” 10 times (each “Hello” on its own line)  Write a loop to print out the numbers from 1 to 20 on a single line  separate the numbers by spaces  end the line when you’re done

49 Find Maximum of N Numbers  Initialization  initialize maximum to something small  Count the numbers  Processing  get the next item  update the max »Math.max returns the bigger of the two numbers you give it int max, n; max = Integer.MIN_VALUE; for(n = 1; n <= N; n++) { num = kbd.nextInt(); num = kbd.nextInt(); max = Math.max(max, num); max = Math.max(max, num);} Integer.MIN_VALUE is the smallest integer Java knows

50 Exercise  Change this loop into a loop to find the minimum value int max, n; max = Integer.MIN_VALUE; for(n = 1; n <= N; n++) { num = kbd.nextInt(); num = kbd.nextInt(); max = Math.max(max, num); max = Math.max(max, num);} What’s the name of the largest integer Java knows? (What do you think’s the name of the largest double Java knows?) What’s the name of the function that finds the smaller of two numbers?

51 Exercise  Change this loop to be data-controlled  stop when negative number is entered int max, n; max = Integer.MIN_VALUE; for(n = 1; n <= N; n++) { num = kbd.nextInt(); num = kbd.nextInt(); max = Math.max(max, num); max = Math.max(max, num);} Enter positive integers below. Enter -1 to end. 10 20 30 40 11 12 13 5 -1 The largest positive number you entered was 40.

52 Questions


Download ppt "Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)"

Similar presentations


Ads by Google