Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Lecture 1.docx
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
704 Кб
Скачать
☆

9.4. Making decisions: the if and if-else statements.

As we know, the if statement has the following form:

if(exp) ins where:

  • exp - an arbitrary expression of type boolean,

  • ins - an arbitrary instruction (including block).

Execution: the instruction ins is executed if and only if the value of the expression exp is true.

The if-else statement has the form:

if(exp) ins1 else ins2 where:

  • exp - an arbitrary expression of type boolean

  • ins1, ins2 - arbitrary instructions (including block).

Execution: the instruction ins1 is executed if and only if the value of the expression exp is true. If the value of the expression exp is false then the instruction ins2 is executed.

The following examples demonstrate the difference between the if and the if-else statements: if (a == b) c = d; c = e; System.out.println( a + " " + b + " " + c + " " + d); and if (a == b) c = d; else c = e; System.out.println( a + " " + b + " " + c + " " + d); The instruction c = d in the first piece of code is to be executed only if the value of the variable a is equal to b. However, independently of this condition, just after the execution of the if statement, the value of the variable e will be stored in the variable c (thus the if statement is not necessary here). Then the values of variables are printed at the command prompt. In the second piece of code the value of the variable c depends on whether a == b or not (exactly one of the assignments will be executed: c = d or c = e). Of course the instructions ins1 and ins2 from the definition may be the if (or if-else) statements allowing nesting of conditions:

char op;

double a, b, r;

...

if (op == '+') r = a + b;

else if (op == '-') r = a - b;

else if (op == '*') r = a*b;

else if (op == '/') r = a/b;

else System.out.println("Incorrect operation code");

Here arises the question: which else corresponds to which if? The rule is simple: to the given else corresponds the first if that precedes it in the same block and is not already matched. Of course indentation of code does not influence matching of if-else pairs.

Here are some common mistakes made when dealing with the if and if-else statements: A. Improper matching of if and else in case of the nested if-else statements. B. The semicolon put after the closing parenthesis of the condition: if (a > b); System.out.println("a > b"); // will execute independently of a>b ! C. Lost the closing brace ending a block: if (a > b) { c = a + b; d = e + f; else c = d + f;

9.5. Multivariant selections done with the switch statement.

In some cases, instead of multiple if-else statements, the switch statement may be applied. It has the following form:

switch (exp) switch_block where:

  • the expression exp must be of type: char, byte, short, or int

  • switch_block is a block consisting of special statements of the following form: case const_expr : ins and default : ins // Note: the "default" label may occur only once

The expression in parentheses (after the switch keyword) is evaluated and its value compared with the values of the constant expressions (contained in parts denoted by the case keyword). Control is transferred to the statement with matching constant expression (the case label). Execution continues from that place until the end of the switch block or the first occurrence of the break or return statement. If no matching constant expression (the case label) is found, then control is transferred to the statement with the default label or - if there is none - to the statement following the switch block. Consider the class SimpleCalc with the method makeOp which carries out arithmetical operations on its attributes - two real numbers.

public class SimpleCalc {

private double a;

private double b;

public SimpleCalc(double x, double y) {

a = x;

b = y;

}

public double makeOp(char op) {

double r = 0;

switch(op) {

case '+' : r = a + b; break;

case '-' : r = a - b; break;

case '*' : r = a * b; break;

case '/' : r = a / b; break;

default : System.out.println("Unknown operation code");

}

return r;

}

}

class SimplecalcTest {

public static void main(String[] args) {

SimpleCalc sc = new SimpleCalc(1.2, 3.7);

System.out.println( sc.makeOp('+'));

System.out.println( sc.makeOp('-'));

System.out.println( sc.makeOp('*'));

System.out.println( sc.makeOp('/'));

}

}

The value of the variable op (of type char) determines the operation carried out by the method makeOp. If, for example, it is the '+' character, then control is transferred to the statement labeled with the case '+'. There the value of the variable r is calculated as a sum of a and b. The break statement leaves the switch block.

It is worth noting that the case labels are constant expressions. The value of such an expression must be known at compile time and may not be modified during the execution of the program. It may be a literal ('+', '*' or 1), a constant (a variable declared final) or an expression consisting of literals and constants (for example: LMAX + 3/LMIN, where LMAX and LMIN are constants). The value of such a constant expression must be of integral type and it must be assignable to the type of the switch expression.

To break the execution of the switch block the break statement or the return statement must be used. Consider the following piece of code: double a = 0.1; switch(n) { case 1 : a = a + 1; case 2 : a = a + 2; case 3 : a = a + 3; } System.out.prinln(a); It prints 6.1 (for n = 1), 5.1 (for n = 2) and 3.1 (for n = 3). In other cases it prints the original value of the variable a (0.1). If our goal is to have 1.1 for n =1, 2.1 for n=2 and 3.1 for n=3 then we must put the break statement after each calculation of a. It breaks the execution of the block and transfers control to the first instruction after the switch block. The case labels and the default label may occur in arbitrary order, but they may not repeat: no two of the case constant expressions may have the same value. Similarly there may not be two default labels. If two switch statements are nested then the case and default labels correspond to the associated switch: switch(i) {     case 1 : switch(testNum(i)) {         case 1 : System.out.println("same one"); break;         case 2 : System.out.println("double one"); break;         default: System.out.println("other one"); break;         }         break;     case 2 : System.out.println("two"); break;     default: System.out.println("other two"); break; } If the testNum method returns the value of its argument multiplied by 2, then with 1 as input i the above instruction prints "double one", whereas with 2 as input i it prints "two". The break statement breaks the execution of the switch block in which it is contained. Using the break statement with a label we can transfer control out of the switch block to the instruction labeled with the given label. This way nested switch statements may be left with a single break statement. Note: the labeled break statement may be used to leave loops too.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]