CMP-MX21: Lecture 4 Selections

43
CMP-MX21: Lecture 4 Selections Steve Hordley

description

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. - PowerPoint PPT Presentation

Transcript of CMP-MX21: Lecture 4 Selections

Page 1: CMP-MX21: Lecture 4 Selections

CMP-MX21: Lecture 4

Selections

Steve Hordley

Page 2: CMP-MX21: Lecture 4 Selections

Overview

1. The if-else selection in JAVA

2. More useful JAVA operators

4. Other selection constructs in JAVA

3. The scope of a variable

Page 3: CMP-MX21: Lecture 4 Selections

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.

Page 4: CMP-MX21: Lecture 4 Selections

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

Page 5: CMP-MX21: Lecture 4 Selections

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 intAn 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

Page 6: CMP-MX21: Lecture 4 Selections

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.

Page 7: CMP-MX21: Lecture 4 Selections

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

Page 8: CMP-MX21: Lecture 4 Selections

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:

The if-else construct and

the switch-case construct

Page 9: CMP-MX21: Lecture 4 Selections

The if-else construct

The if-else construct has the following general form:

if (expression)

{

one or more statements;

}

else

{

one or more statements;

}

The expression is first evaluated

If the expression is true this first set of statements is carried out

Otherwise this second set of statements is carried out

Page 10: CMP-MX21: Lecture 4 Selections

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

Page 11: CMP-MX21: Lecture 4 Selections

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 (})

Page 12: CMP-MX21: Lecture 4 Selections

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

Page 13: CMP-MX21: Lecture 4 Selections

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 ...

Page 14: CMP-MX21: Lecture 4 Selections

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;

}

Page 15: CMP-MX21: Lecture 4 Selections

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;

}

Page 16: CMP-MX21: Lecture 4 Selections

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”);

}

Page 17: CMP-MX21: Lecture 4 Selections

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 ==)

Page 18: CMP-MX21: Lecture 4 Selections

The “is equal to” operator

In fact these two operators have a very different meaning in JAVA

operation == ‘+’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

== is the “is equal to” or “equality” operator

= is the assignment operator

Page 19: CMP-MX21: Lecture 4 Selections

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 = ‘+’){

...

incompatible type for if. Can’t convert int to booleanif(operation=‘+’) ^

Will give this error:

We will ignore why we get this particular error message for now!

Page 20: CMP-MX21: Lecture 4 Selections

Other useful operators

(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) true if lhs is not equal to rhs

Page 21: CMP-MX21: Lecture 4 Selections

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 { ^

Page 22: CMP-MX21: Lecture 4 Selections

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 { ^

Page 23: CMP-MX21: Lecture 4 Selections

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);

}

‘else’ without ‘if’else { ^

Forgetting the curly brackets when there

are multiple statements after the

if will also lead to the same

compilation error

Page 24: CMP-MX21: Lecture 4 Selections

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);

}

Page 25: CMP-MX21: Lecture 4 Selections

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

Page 26: CMP-MX21: Lecture 4 Selections

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;

}

Page 27: CMP-MX21: Lecture 4 Selections

The switch construct line by line

switch (test_expression){

A switch construct always begins with a line of the form:

When the program reaches this line test_expression is evaluatedProgram 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:

Page 28: CMP-MX21: Lecture 4 Selections

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

Page 29: CMP-MX21: Lecture 4 Selections

The switch construct line by line

case constant_value2:

If test_expression is not equal to constant_value1 program execution jumps to the next case statement:

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

Page 30: CMP-MX21: Lecture 4 Selections

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

Page 31: CMP-MX21: Lecture 4 Selections

An exampleIn our calculator program selecting the appropriate operation can be done with a switch construct:

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”);

}

Page 32: CMP-MX21: Lecture 4 Selections

Some notes

case constant_value1:

case constant_value2:

statements;

break;

case constant_value3:

...

The same set of statements can be executed for multiple values of the test_expression in the following way:

In this case when test_expression has the value constant_value1 or constant_value2, the same set of statements are performed

Page 33: CMP-MX21: Lecture 4 Selections

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;

case constant_value3:

...

In this case, when test_expression is

equal to constant _value1

the statements after the first and the

second case statement are

executed

Page 34: CMP-MX21: Lecture 4 Selections

Some notes

switch (test_expression){

case constant_value1:

statements;

break;

case constant_value2:

statements;

break;

...

}

The default statement is optional. If no statements are to be executed in the default case, this clause can be omitted.

Page 35: CMP-MX21: Lecture 4 Selections

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?

Page 36: CMP-MX21: Lecture 4 Selections

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{

public static void main( String [] args ){

// Variable declarations

int a;

double b;

// Program statements

...

}

}

Page 37: CMP-MX21: Lecture 4 Selections

The scope of a variableIn fact, we can make variable declarations anywhere in our code:

class myProgram{

public static void main( String [] args ){

int a;

double b;

...

if (a>b){

int i;

a=a+i;

}

double c;

c= (double)a*b;

}

}

Page 38: CMP-MX21: Lecture 4 Selections

The scope of a variableThe 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: { }

Page 39: CMP-MX21: Lecture 4 Selections

The scope of a variable

class myProgram{

public static void main( String [] args ){

int a;

double b;

...

if (a>b){

int i;

a=a+i;

}

double c;

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

Page 40: CMP-MX21: Lecture 4 Selections

Some notesNote: a variable cannot be referred to before it is declared, even if the reference is within the variable’s scope:

class myProgram{

public static void main( String [] args ){

a=10;

int a;

}

This line will not compile

Referring to a variable which is out of scope also results in a compilation error:

if (a>b){

int a;

a++;

}

a=a*5;This line will not compile

Page 41: CMP-MX21: Lecture 4 Selections

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

Page 42: CMP-MX21: Lecture 4 Selections

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

Page 43: CMP-MX21: Lecture 4 Selections

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:

==, !=, >, <, >=, <=