Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Multivariant selections done with the switch statement.

Useful examples | Defining attributes of objects | Defining operations on objects (methods) | Defining methods of object creation (constructors) | Static members | Packages and imports | Scope of an identifier. Local variables. Access control. | Structure of a program. Running an application. | A brief survey of control statements. | Comparison operators and expressions |


Читайте также:
  1. Channels switch soap operas commercials objective
  2. Config)# interface gigabitethernet 1/1(config-if)# no switchport
  3. Ex. 2. For each main argument, think of two different supporting ideas to back it up. Write your ideas after each statement. The first one is done for you.
  4. Listen to the text and chose the most precise variant to complete each statement.
  5. Microsoft Visual Studio LightSwitch 2012
  6. Speaking at the United Nations General Assembly, President Obama addressed the ongoing conflict in Syria and called for oppressive regimes to switch to democracy.

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

9.6. The conditional operator?:

The conditional operator?: takes three arguments - expressions. It is used in the following way:

e1? e2: e3

The expression e1 must be of boolean type. The other expressions (e2 and e3) must be of the same type or of types convertible to some common type.

The expression built with the conditional operator is called the conditional expression.
It is evaluated as follows. The expression e1 is evaluated. If it is true then the expression e2 is evaluated and its value becomes the value of the whole expression. The expression e3 is ignored in such case. If e1 is false, then the expression e2 is ignored and the value of the e3 becomes the value of the whole conditional expression.

The precedence of the?: operator is low (but higher than the assignment operators). It is right-associative. Low precedence allows omitting parentheses although it is worth using them for greater clarity.

The conditional expression may replace the if-else statement in many simple cases:

In the context: int a = 1,d; float b = 0.7, c;..... int func1() {...} int func2(int) {...} void func4() {... }
The if statement Corresponding conditional expression
if (a > b) c = a + 2; else c = b; c = a > b? a + 2: b;
if (a < b) c = a + 2; else d = b + 2; a < b? c = a + 2: d = b + 2;
if (b>0) d= func2(a) + 2; else b *= 3.3; b > 0? d = func2(a) + 2: b *= 3.3;
if (b > 0) d = func1(); else a++; b > 0? d = func1(): a++;
if (b > 0) func4(); else d = a + 7; This cannot be noted as a conditional expression because the operand e2 is of type void whereas the operand e3 is of type int.

 

As we see, the replacement of the if statement with a conditional expression is not always possible.

But the conditional operator is not meant to replace the if statement.

The main advantage of the conditional operator is that it may be apllied where the if statement cannot or where the application of the if statement would seem awkward.

Consider the initialization of a variable (a common example):

int x = (a > b? 1: 0);

 

Summary

The lecture discusses in detail the statements and the operators designed to make decisions in a program.
They constitute the essence of programming.

Exercises

  1. Write a program which would translate the numeric grades (A, B, C, D, E, F) given in input dialog into descriptive grades:
    1. excellent
    2. good
    3. fair
    4. poor
    5. below standard
    6. fail

Separate data entering from translation and result writing, protect the program from entry errors, by informing a user that he or she has entered improper data and asking for the correction of that data.

  1. Modify the class Publication from the lectures 7-8 so as to make setting of the non-positive prices and setting of non-positive quantities of purchase and sale impossible. How a program should react on such errors? In a test program assure interactive (using dialogs) creation of publication objects (with verification of the correctness of input data), setting their prices, purchase and sale of publications and reporting about changes in the bookshop.
  2. Write a program that checks whether the given number fits in on of the intervals: 1-10, 11-100, 101-1000, 1001-10000 or is less than 0 or greater than 10000.
  3. Write a program asking the user to input 5 strings and checking whether there are two equal among them. It should print the number of equal strings.

 



Дата добавления: 2015-11-16; просмотров: 47 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Logical operators and expressions| A . Nephrosis

mybiblioteka.su - 2015-2024 год. (0.009 сек.)