1 / 43

CMP-MX21: Lecture 4 Selections

CMP-MX21: Lecture 4 Selections. Steve Hordley. Overview. 1. The if-else selection in JAVA. 2. More useful JAVA operators. 3. The scope of a variable. 4. Other selection constructs in JAVA. A problem.

carr
Download Presentation

CMP-MX21: Lecture 4 Selections

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. CMP-MX21: Lecture 4Selections Steve Hordley

  2. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 3. The scope of a variable 4. Other selection constructs in JAVA

  3. A problem Extend the simple calculator program from the previous lecture to provide the user with the option of using different operators. The program should read from the keyboard two floating point numbers and the operation which is to be performed on them and should display the result of the operation.

  4. Designing a solution Program inputs: two numbers and an operator Program output: a single number Data representation: input numbers and the result are floats. What type should we use for the operator? Tasks to be performed: 1. Read two numbers from the keyboard 2. Read an “operation” from the keyboard 3. Apply the operation to the two numbers 4. Write out the result

  5. Representing an operator How should we represent the user’s choice of operator in this program? One way would be to provide the user with a numbered list of possible operators and to represent an operator by its number In this case we would represent an operator using an int An alternative would be to allow the user to directly enter the symbol for the appropriate operator e.g. * or + or - etc. In this case we would represent an operator by a char

  6. Applying the relevant operator However we represent our operator we must deal with the fact that our program needs to different things depending on what the user inputs Essentially what we would like to do is the following: if operator is ‘*’ then multiply the two numbers otherwise, if operator is ‘/’ then divide the two numbers otherwise, if operator is ‘+’ add the two numbers etc.

  7. Pseudo-code Note, what we have written here is not JAVA code but simply an outline of the process we want to follow. We call this outline pseudo-code. It is a mixture of English and JAVA language As our programs become more complex we will often outline the general operation of the program using pseudo-code of this form

  8. Selections in JAVA To convert this pseudo-code into real JAVA code we need to use one of JAVA’s selection constructs We will look at two selection constructs: Theif-elseconstruct and theswitch-caseconstruct

  9. The if-else construct The if-else construct has the following general form: The expression is first evaluated if (expression) { one or more statements; } else { one or more statements; } If the expression is true this first set of statements is carried out Otherwise this second set of statements is carried out

  10. An example int a=7, b=4; if (a>b) { System.out.println(“a is bigger than b”); } else { System.out.println(“b is bigger than a”); } ... This expression evaluates to true So this statement is carried out Program execution then jumps to here

  11. Some notes We can use an if statement on its own, without a corresponding else: if (expression) { one or more statements; } In this case the statements between the curly brackets {} are evaluated if the expression is true. Otherwise, the program continues directly after the closing bracket (})

  12. Some notes Sometimes we only want to execute a single statement after the if or the else. In this case, the curly brackets are unnecessary: if (expression) a single statement; else a different single statement; But, whenever we have more than a single statement after an if or an else the curly brackets are required. Without them our program might not compile and if it does, it will not produce the result we expect

  13. Nested if-else statements This simple form of the if else construct deals with either/or selections where we have only two choices Often we will have multiple choices - we will execute different pieces of code depending on more than just a single condition or expression We can handle this case by using nested if-else statements ...

  14. if (expression1) { one or more statements; } else if (expression2) { one or more statements; } else if (expression3) { one or more statements; else { one or more statements; }

  15. Suppose we want our calculator to perform one of four types of operation: addition, subtraction, division or multiplication. We can achieve this with the following code: if (operation == ‘+’){ theResult = a+b; } else if (operation == ‘-’){ theResult = a-b; } else if (operation == ‘*’){ theResult = a*b; } else if (operation == ‘/’){ theResult = a/b; }

  16. Some notes In this example we should really add a final else clause to deal with the case that the user enters an operator other than the four we have handled: if (operation == ‘+’){ theResult = a+b; } ... else if (operation == ‘/’){ theResult = a/b; } else{ System.out.println(“Invalid operator”); }

  17. The “is equal to” operator In the example we have just seen we used the following expression: if (operation == ‘+’){ ... In English this statement means: “if the variable operation is equal to ‘+’ Intuitively we might be tempted to write: if (operation = ‘+’){ ... (a single = rather than two ==)

  18. The “is equal to” operator In fact these two operators have a very different meaning in JAVA Tests whether operation is equal to ‘+’ and returns a boolean value of true if it is and false otherwise operation == ‘+’ Assigns the right-hand side of the equals sign to the left-hand side operation = ‘+’ == is the “is equal to” or “equality” operator = is the assignment operator

  19. The “is equal to” operator Note that using the = rather than the == operator in an if statement will result in a compilation error: if (operation = ‘+’){ ... Will give this error: incompatible type for if. Can’t convert int to boolean if(operation=‘+’) ^ We will ignore why we get this particular error message for now!

  20. Other useful operators true if lhs is not equal to rhs (a!=b) true if lhs is greater than rhs (a>b) true if lhs is less than rhs (a<b) true if lhs is greater than or equal to rhs (a>=b) true if lhs is less than or equal to rhs (a<=b)

  21. Some common errors If we get the syntax of the if-else construct wrong it will lead to compilation errors or sometimes to a program that compiles but does not perform as expected: if (operation == ‘+’); { theResult = a*b; } else{ theResult = a/b; } Putting a semi-colon at the end of an if statement is a common error which leads to a compilation error ‘else’ without ‘if’ else { ^

  22. Some common errors if (operation == ‘+’) { theResult = a*b; }; else{ theResult = a/b; } Putting a semi-colon at the end of block of statements connected to an if leads to the same compilation error: ‘else’ without ‘if’ else { ^

  23. Some common errors if (operation == ‘+’) theResult = a*b; System.out.println(“The result is”+theResult); else{ theResult = a/b; System.out.println(“The result is”+theResult); } Forgetting the curly brackets when there are multiple statements after the if will also lead to the same compilation error ‘else’ without ‘if’ else { ^

  24. Some common errors if (operation == ‘+’) theResult = a*b; System.out.println(“The result is”+theResult); The above code will compile but will not do what is intended: the first line will be performed if the condition is true. But the second line will always be carried out Curly brackets are required for correct operation: if (operation == ‘+’){ theResult = a*b; System.out.println(“The result is”+theResult); }

  25. Other selection constructs The if statement is sufficient to perform any selection in JAVA Note we do not strictly speaking even require the else, but using it often leads to code which is more efficient and also easier to read JAVA also provides an alternative selection construct: the switch statement The switch construct is less general than the if-else, but is sometimes a more natural way to solve a particular problem

  26. The switch construct The switch statement has the following general form: switch (test_expression){ case constant_value1: statements; break; case constant_value2: statements; break; ... default: statements; }

  27. The switch construct line by line A switch construct always begins with a line of the form: switch (test_expression){ When the program reaches this line test_expression is evaluated Program execution then goes to the first case statement: case constant_value1: If constant_value1 is equal to test_expression then the statements following the case statement are evaluated:

  28. The switch construct line by line switch (test_expression){ case constant_value1: statements; break; case constant_value2: statements; break; ... default: statements; } Statements are executed until the break statement is reached Program execution then jumps to the end of the switch construct

  29. The switch construct line by line If test_expression is not equal to constant_value1 program execution jumps to the next case statement: case constant_value2: If test_expression is equal to constant_value2 the program statements following the case statement are executed until a break statement is reached Program execution then jumps to the end of the switch construct

  30. The switch construct line by line If test_expression is not equal to any of the case constant values program execution jumps to the default line: ... default: statements; } The statements after the default statement are then executed

  31. In our calculator program selecting the appropriate operation can be done with a switch construct: An example switch (operation){ case ‘+’: theResult = a+b; break; case ‘-’: theResult = a-b; break; case ‘*’: theResult = a*b; case ‘/’: theResult = a/b; default: System.out.println(“Invalid Operator”); }

  32. Some notes The same set of statements can be executed for multiple values of the test_expression in the following way: case constant_value1: case constant_value2: statements; break; caseconstant_value3: ... In this case when test_expression has the value constant_value1 or constant_value2, the same set of statements are performed

  33. Some notes Once a case statement is true program execution continues until the next break statement is reached: case constant_value1: statements; case constant_value2: statements; break; caseconstant_value3: ... In this case, when test_expression is equal to constant _value1 the statements after the first and the second case statement are executed

  34. Some notes The default statement is optional. If no statements are to be executed in the default case, this clause can be omitted. switch (test_expression){ case constant_value1: statements; break; case constant_value2: statements; break; ... }

  35. Some notes Often, both the if-else and the switch-case constructs can be used to perform our selection task (as in the example we have just seen) When deciding which of the two constructs to use we should be guided by the particular problem we are trying to solve. We need to think about: What is the natural way to perform the selection? Which selection will lead to the most simple (easiest to read) code?

  36. The scope of a variable So far in our programs we have been declaring variables at the start of our programs and then using them anywhere else throughout the program: class myProgram{ publicstaticvoidmain( String [] args ){ // Variable declarations int a; double b; // Program statements ... } }

  37. The scope of a variable In fact, we can make variable declarations anywhere in our code: class myProgram{ publicstaticvoidmain( String [] args ){ int a; double b; ... if (a>b){ int i; a=a+i; } double c; c= (double)a*b; } }

  38. The scope of a variable The scope of a variable is the region of the program in which a variable can be referred to by its simple name A variable’s scope is determined by the block of code in which it is declared A block of code is any section of a program delimited by a set of curly brackets: { }

  39. The scope of a variable class myProgram{ publicstaticvoid main( String [] args ){ inta; double b; ... if (a>b){ int i; a=a+i; } doublec; c= (double)a*b; } } Here a and b have scope between the red brackets (they can be referred to anywhere in the method main) i has scope within the orange brackets c has scope within the red brackets

  40. Some notes Note: a variable cannot be referred to before it is declared, even if the reference is within the variable’s scope: class myProgram{ publicstaticvoid main( String [] args ){ a=10; inta; } This line will not compile Referring to a variable which is out of scope also results in a compilation error: if (a>b){ inta; a++; } a=a*5; This line will not compile

  41. Some notes In JAVA, variables are created (memory is reserved) when JAVA encounters the variable declaration When a variable goes out of scope (the end of the code block in which it is declared is reached) JAVA destroys the variable: the memory used to hold it is freed and can be used for something else. So, defining variables when and where they are needed makes JAVA programs more efficient in terms of the memory they use

  42. A summary In this lecture we have introduced the idea of re-usable code. We have seen how code written by others can be incorporated into our own programs. We saw how re-using code in this way simplifies our own code by looking at the example of reading data from the keyboard. We introduced JAVA’s selection constructs: the if-else construct and the switch-case construct. Finally we introduced the concept of the scope of a variable

  43. A summary You should now be familiar with the meaning of the following words from the JAVA language: if, else, switch, case, default, break In addition you should understand the meaning of and how to use the following operators: ==, !=, >, <, >=, <=

More Related