Presentation is loading. Please wait.

Presentation is loading. Please wait.

Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.

Similar presentations


Presentation on theme: "Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if."— Presentation transcript:

1 Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else statements and includes loops (introduced later today) with nested if- else statements –what if we have a list of possible actions to take based on an input or computed value? –for instance, we ask the user to input their age before playing a game if they enter anything < 0, we want to output an error message if they enter between 1 and 8, we might say that they are too young to play this game if they enter between 18 and 24, we might tell them to grow up and quit playing games if they enter anything over 24, we might laugh at them any other age is ok for our game –how do we design the logic to handle such a situation?

2 Nested Statements Let’s try to implement the previous example: –age < 0: error –age between 1 and 8: too young –age between 9 and 17: ok –age between 18 and 24: too old –age > 24: really really old Can we do this with an if statement or an if-else? No –we could solve this with 5 if statements, or with a nested if-else statement how do we test to see if an age is between 9 and 17? the conditions we’ve already seen have only tested a variable to one value, not two this will take some modification –or, we can use nested statements, this means that we have an if statement or an if-else statement as the statement inside of the if-clause or the else-clause or both

3 Grade Example if (age < 0) output=“error”; else if(age<=8) output=“too young”; else if(age<=17) output=“ok”; else if(age<=24) output=“too old”; else output=“really really old”; if(age < 0) output=“error”; if(age<=8) output=“too young”; if(age<=17) output=“ok”; if(age<=24) output=“too old”; else output=“really really old”; Nested approach Note: indentation is not needed, its there for program readability Alternate approach – what is Wrong with this code? If you are 16, what will output be? We could solve this problem by reordering the if statements in the opposite order, but the new code would be inefficient – why?

4 import javax.swing.*; public class MinOfThree; { public static void main(String[] args) { int num1, num2, num3, min = 0; num1 = Integer.parseInt (JOptionPane.showInputDialog (null, “Enter a number”)); num2 = Integer.parseInt (JOptionPane.showInputDialog (null, “Enter a second number”)); num3 = Integer.parseInt (JOptionPane.showInputDialog (null, “Enter a third number”)); if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println( " Minimum value is: " + min); } Another Example Notice the logic here, if num1 < num2, then we compare num1 and num3, to see which is smaller, if num1 < num3 then num1 is smallest (we already know num1is smaller than num2) if num1 is not less than num2, we compare num2 and num3

5 The Switch Statement An alternate approach to using the nested if-else structure is an instruction called switch We will use the switch statement if we are testing a single variable against a list of values Structure: –switch (variable) { case val 1 : statement 1 ; case val 2 : statement 2 ; case val 3 : statement 3 ; … case val last : statement last ; default : defaultstatement; } Compare variable with val1, val2, … and pick which statement to execute based on which value the variable matches

6 Switch Example switch (grade) { case ‘A’ : comment = " gold star " ; break; case ‘B’ : comment = " silver star " ; break; case ‘C’ : comment = " bronze star " ; break; case ‘D’ : comment = " no star " ; break; case ‘F’ : comment = " demerit " ; break; default : comment = " error, illegal letter grade! " ; } In this example, comment is a String which is assigned a value based on the student’s letter grade default is used as an error checking mechanism here – if reached, then the grade is an illegal grade NOTE: the word break is used to exit the switch statement, default is used as a final else clause for the switch

7 Which Statement Should You Use? When it comes to selection, you have five possibilities: –if statement –if-else statement –group of if statements –nested if-else statement –switch statement If there is only one action, then use the if statement If two actions, one if the condition is true, one if the condition is false, then use the if-else statement If you have a series of possibilities, which should you use? –Switch statement if the possibility is based on a single variable and the variable is an integral data type (integer, character or a user defined type that is ordinal) –Otherwise, use the nested if-else statement

8 Compound Conditions Recall the code to the right, what is wrong with it? –there is improper logic –we need to replace this condition with a compound condition test two things: if age > previous upper limit and also if age <= current upper limit –we create compound conditions by connecting them together with logic operators –there are 3 forms of logic operators used in Java: and (denoted as &&) – all conditions must be true for the compound condition to be true or (denoted as ||) – at least one condition must be true for the compound condition to be true not (denoted as !) – the item is inverted (true becomes false, false becomes true) if(age < 0) output=“error”; if(age<=8) output=“too young”; if(age<=17) output=“ok”; if(age<=24) output=“too old”; else output=“really really old”; if (age > 8 && age <=17) output=“ok”;

9 import javax.swing.*; public class Grades { public static void main(String[] args) { int test1, test2, test3, total; float average; char letterGrade; test1 = Integer.parseInt(JOptionPane. showInputDialog(null, “Enter first test score”)); test2 = Integer.parseInt(JOptionPane. showInputDialog(null, “Enter second test score”)); test1 = Integer.parseInt(JOptionPane. showInputDialog(null, “Enter third test score”)); if(test1 > = 60 && test2 > = 60 && test3 > = 60) // compute total but total= test1 + test2 + test3;// total is the 3 test scores else total = 0;// only if student has average = (float) total / 3;// passed all 3 exams if (average >= 90.0) letterGrade = ‘A’;// otherwise total = 0 else if (average >= 80.0) letterGrade = ‘B’; else if (average >= 70.0) letterGrade = ‘C’; else if (average >= 60.0) letterGrade = ‘D’; else letterGrade = ‘F’; System.out.println( " Students average is " + average + " for a grade of " + letterGrade); } Example: Computing Grades

10 Repetition What happens if we want to do some action multiple times? –For instance, we want to compute multiple students grades? We could run our grade program several times But this is tiresome and also does not allow us to compute things like class averages or sort the scores or anything like that –We instead need instructions that allow code to be repeated – thus repetition control statements –There are three forms of repetition statements in Java: While loops Do loops For loops

11 The While Statement The while statement evaluates a condition –if that condition is true, the body of the while statement is executed and the process is repeated –If the condition is false, the rest of the statement is skipped and control continues with the next instruction after the while statement while ( condition ) statement; while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. statement true condition evaluated false

12 Example Let’s write a loop that will compute the powers of 2 that are less than 1000000 –We start with a variable set equal to 1 –We loop while that variable <=1000000 –Inside the loop, we print the value of the variable and then multiply it by 2 Notice that since the loop “body” is more than a single statement, we enclose it in { } to make it a block int value = 1; while (value < 1000000) { System.out.println(value); value *= 2; } outputs: 1 2 4 8 16 32 64 … 524288

13 Sentinel Values In the prior example, we iterated until we reached an upper limit We will often use While loops to repeat some action such as: input some value, perform a calculation, output a result, repeat until the user is done –How do we know if the user is done? –We could ask the user or we could base the decision on the input value – this is known as a sentinel value Example: input a list of integers until the user enters a negative number, and compute the sum of these numbers

14 Sum Example int value, sum; … sum = 0; value = Integer.parseInt(JOptionPane.showInputDialog (null, “Enter a positive integer, negative number to quit”)); while (value >= 0) { sum += value; value = Integer.parseInt(JOptionPane.showInputDialog (null, “Enter next positive integer, negative number to quit”)); } System.out.println( " The sum of the numbers you entered is " + sum); value < 0 is our sentinel for the loop Notice that we repeated these Instructions – why? Initialize sum before we enter the loop

15 A slightly different version int value, sum; … sum = 0; value = Integer.parseInt(JOptionPane.showInputDialog (null, “Enter a positive integer, negative number to quit”)); while (value >= 0) { sum += value; } System.out.println( " The sum of the numbers you entered is " + sum); Notice in this version we don’t ask for the next value – this means that value never changes – if it never changes, then it is always the original value, if that value was >= 0, it will always be >= 0 and thus the loop will never stop – this is an infinite loop

16 Infinite Loops Careless (and even careful) programmers will write infinite loops This is a major problem when using the while loop –The basic idea behind the loop is to continue executing while a condition is true If that condition is based on an input value, then the program must input a new value during each iteration so that the user can change the value to one that exits the loop Otherwise, the value never changes and the loop never stops! Exiting an infinite loop –if you suspect that your program is caught in an infinite loop, about your only recourse is to stop the program Press control-C on the keyboard

17 Computing an Average int number, count, sum; float average; sum = 0; count = 0; number = Integer.parseInt(JOptionPane. showInputDialog(null, “Enter a number, 0 to end”)); while (number > 0) { sum += number; count++; number = Integer.parseInt(JOptionPane. showInputDialog(null, “Enter a number, 0 to end”)); } average = (float) sum / count; System.out.print( " The average of your " + count); System.out.println( " numbers is " + average); This program is similar to the sum program from before, but we are also counting the number of inputs using the count variable 0 (or any negative number) is our sentinel value Notice that average is not formatted, our output might look messy!

18 The do Loop The do loop is similar to the while loop but is a post-test loop, the while loop is a pre-test loop The Do loop starts with the reserved word do followed by the loop body and then the reserved word while and the condition –The difference is the flow of control – here, the condition is not evaluated until after the body of the loop executes do { statement; } while ( condition ) Uses both the do and whilereservedwords true condition evaluated statement false

19 While vs. Do The only difference between these two statements is when the condition is evaluated –While: evaluated before executing the loop body –Do: evaluated after executing the loop body If you want to automatically execute the loop body at least once, use the Do loop If you don’t want to do the body if the condition is not true, use the While loop statement true condition evaluated false true condition evaluated statement false

20 Using Loops to Verify Input Consider a situation where we want the user to input one of a set of values that constitute a legal input What if the user enters an illegal input? –Example: input a non-negative integer and take the square root –If x < 0, we would get a run- time error when the sqrt operation is invoked! A solution to this problem is to place the prompt and input statements inside a loop that only terminates once the user has entered the right value –We will use a do statement for this since we will want the user to input the value at least one time x = Integer.parseInt(JOptionPane.showInputDialog(null, " Enter a non-negative integer " )); y = Math.sqrt((double) x); do { x = Integer.parseInt(JOptionPane. showInputDialog(null, " Enter a non-negative integer " )); } while (x < 0); y = Math.sqrt((double) x);


Download ppt "Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if."

Similar presentations


Ads by Google