You get a bonus - 1 coin for daily activity. Now you have 1 coin

Introducing the Eclipse Shell

Lecture



Purpose, Features, and Benefits of Eclipse

Eclipse is an extensible IDE (integrated development environment). IDE is a conveniently organized set of tools needed to work on a software project.

Eclipse is a universal platform that can be used to develop applications in any programming language (for example, you can use the Python language after setting up a Pydev connection (http://sourceforge.net/projects/pydev/), but Java is originally native to Eclipse (on which, by the way, Eclipse itself is written).

The most important features of Eclipse are:

  1. Cross platform Eclipse runs on all common platforms: Windows, Linux and MacOS X. More importantly, its functions are the same on each of these platforms.
  2. Universality and extensibility. Eclipse implements the ability to use various tools developed by third-party programmers.
  3. Open and free. Eclipse is an open source project (i.e., its source code is available to anyone and anyone can join the development of this tool). Eclipse has an active community that is constantly working to improve the program and expand its capabilities.

Eclipse Workbench

The first thing you see when you start Eclipse is a dialog box that allows you to choose where the workspace will be located. The workspace is the directory in which your work will be saved.

After selecting the workspace, the initial page will appear on the screen, with suggestions to view tutorials, examples, etc. Select Workbench and you will be taken to the Workbench window where your further work will take place.

The main components of the working environment are views (views), editors (editors) and projections or perspectives.

  Introducing the Eclipse Shell A view is a small section within the workbench that serves to navigate through a certain category of objects (such as resources or packages), open editors, display properties of active editors. For example, the Navigator view shows projects and other resources, and the Bookmarks view displays all the bookmarks in Workbench along with the names of the files with which these bookmarks are associated. The illustration shows the upper right corner of the working environment with an active Outline view.

All changes made to views are saved immediately.

Another type of Workbench visual component is editors , which are used to view and edit a certain resource (for example, program code). When you select a resource, the appropriate editor appears. For example, open any text document (with the extension .txt) with the command File -> Open File ... and you will see the built-in editor of plain unformatted text. If you type something in this editor, an asterisk appears on its tab, where the file name is written. It means that the editor contains not saved changes. They will be saved if you press Ctrl + S or select File -> Save.

There are many useful views that are added to the workbench window with the command Window -> Show View. However, instead of adding them one by one, it is more convenient to switch the perspective view. A projection (or perspective ) is a set of views and editors specially selected to perform a certain task. Once launched, Eclipse opens a Java perspective that is configured to write the program itself. Debugging is often used to debug a program. You can switch the projection using the Window -> Open Perspective command. The name of the current projection is displayed in the upper right corner of the working environment (see figure).

First java program

Before programming, you need to create a project in which Eclipse will store all the resources related to your program.

To create a project, run the command File -> New -> Project. In the window that appears, select Java Project and click "Next." Specify the name of your project. Please note that a folder with the name of your project will be created in the directory that you specified as a workspace (unless, of course, you change the settings in this window, which we will not do for the first time). Click "Finish".

Now in the PackageExplorer view, your project is on the left side of the workbench. You can delete it at any time by right-clicking on its name and selecting Delete. After that, Eclipse will ask whether to destroy the folder with the project files at the same time (if necessary, you can also destroy it).

If you have not deleted a project, you can add files and folders to it using the context menu commands New -> File and New -> Folder, respectively. If the project is large, then it needs a structure of nested folders. But in the case of a Java project, things are a little different. The point is that Java program fragments are grouped into packages , and a separate folder is created for each package. The package is created by the command New -> Package. For the package, too, need to come up with a name. As a result, a new folder with this name will be created in the project folder. You can check.

Viewing project resources can be more convenient using the Navigator view. Open it with the command Window -> Show View. You will see that in addition to the project and package directories, Eclipse has created two auxiliary files .classpath and .project. They can easily be opened in the editor, but they are not of particular interest to us now.

A Java program always consists of one or more classes . You can create a class with the command New -> Class in the context menu of the Navigator view (or the Package Explorer, does not matter). When creating a class, you must select the package to which it will belong (select the package you just created) and come up with a name for it. The names of classes are usually started with a capital letter. If you do not follow this rule of good tone, Eclipse will issue a warning, but nothing terrible will happen.

For our purposes, it is useful to put a tick in the section “What methods do you want to create in your class?” Opposite the option public static void main (String [] args). As a result, the method (function) main () will be generated in the class body. Java requires that at least one of the program's classes have a method with such a header. That he will be executed at the start of the program.

As a result of our actions, a file with the name of our class and the extension .java will be created in the package folder. Eclipse opens a code editor that displays the contents of this file. It will be similar to the following (the package and class names may, of course, differ):

package mainPack; public class MyClass { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }

Commands that make up the function body can be written instead of the automatically generated comment // TODO Auto-generated method stub. We will write only one command that will display the classic string “Hello, world!”:

System.out.println("Hello, world!");

It remains to run the program. To do this, run the Run -> Run command and get a dialog box with non-trivial launch settings. In the left part of this window, select Java Application (Java application). After a bit of thinking, Eclipse will find our class containing the main() method and suggest starting the program with it (the names of our project and our class should appear on the Main tab in the right part of the window). In addition, the programmer has several bookmarks. For example, the second of them, Arguments, is proposed to enter command line parameters (if the program is designed to be called from the command line with parameters). For our simple program, nothing else needs to be specified. Just click the Run button.

As a result of the program, data is output to the so-called console. In the MS DOS operating system, the entire monitor screen served as a console. Eclipse opens the Console view to us, in which (if everything is done correctly) and the line "Hello, world!" - the result of the output of our program.

Now to restart the program (for example, if we decide to make some changes to it or need to be shown to the teacher), you can go an easier way - run the Run -> Run Last Launched command (run the previous application again) or simply press Ctrl + F11.

Java syntax basics

Definitions

A literal is a constant of some type that does not have a name, but is indicated by the record itself, for example: 0, 145, 'a', "Hello, world!".

Operator is the smallest autonomous part of a programming language (also called an instruction or a command) capable of executing independently and bearing an independent meaning. An example would be a display statement or a loop statement. The program is usually a sequence of statements (commands, instructions).

Operation - an action on one or more (most often two) values ​​- operands, leading to the appearance of a new value - the result of an operation. An operation, as a rule, does not make sense outside the context of any operator. For example, it makes no sense to write 3+4 as an independent command, since the calculated result of the operation will be lost immediately. But the command x = 3+4; (using the result of an operation in an assignment statement) or System.out.println(3+4); (transfer of the result to the method as a parameter) is fully justified.

The operand is the value involved in the operation.

Method (function) - part of the program that has its own name. This name can be used in the program as a command (this command is called a method call). When the method is called, the commands of which it consists are executed. A method similar to an operation can return a result value.

An expression is a sequence of operations and calls to methods executed in a particular order (by priority of operations, taking into account the brackets), which gives a certain value when calculating.

A variable is a named area of ​​computer memory in which a program can store data of a certain type (called a variable value ) and access this data using the variable name.

Concepts of the program and algorithm (repetition)

Attention! At this stage of training you should already have knowledge of this topic. If they are not, and materials for repetition are incomprehensible or insufficient, you will not cope with tasks! It is urgent to refer to the literature on this topic.

Related Literature:

1. School textbook computer science.

Basic algorithm constructions (repetition)

Attention! At this stage of training you should already have knowledge of this topic. If they are not, and materials for repetition are incomprehensible or insufficient, you will not cope with tasks! It is urgent to refer to the literature on this topic.

Related Literature:

1. School textbook computer science.

Basics of Java Syntax

  1. The Java language distinguishes between uppercase and lowercase letters. This means that the names of all functions and keywords should be written down exactly as they appear in the examples and references.
  2. Each command (statement) in Java must end with a semicolon.
  3. A Java program consists of one or more classes . Absolutely the entire functional part of the program (that is, what it does) must be placed in the methods of various classes. (The class and method, as concepts of object-oriented programming, will be considered in the third lesson. The syntax of classes will also be reviewed there. In the first exercises, use the classes that Eclipse generates by default.)
  4. Classes are grouped into packages.
  5. At least in one of the classes there must be a main() method, exactly the same as in the example we considered. (At first, it is not necessary to understand or try to remember the correct spelling of this method - Eclipse will generate everything by itself if you put the necessary tick.) This method will be executed first.

In the simplest case, a program can consist of one (or even not one) package, one class inside the package, and a single main() method inside the class. Program commands will be recorded between the line.

public static void main(String[] args) {

and a closing brace } , denoting the end of the method body. This approach should be followed when performing the simplest exercises.

Comments

Comments are explanatory labels that programmers use to improve code clarity. When compiling the program, comments are ignored, so anything can be written in them. The main thing is to show that this inscription is a comment and should not be interpreted as commands of the program. In Java, this is done by one of the following images:

  1. Two slashes are put //. From this point to the end of the line, you can write anything you want - Java will take it as a comment.
  2. At the beginning of the comment the characters / * are put, and at the end - * /. In this case, the comment can take any number of lines.
  3. Highlighted comments for documentation , which are placed between the markers / ** and * /. Their use will be discussed later.

Rules for writing literals

about different forms of writing literals

Integers (integer literals) in Java can be written in the usual way in decimal form: 12345, +4, -11.

In addition, you can write integers in octal form, starting with zero (0777, -056) and in hexadecimal form, starting with zero and the x letter (0xFFFF, 0x14, 0xA1BC).

Valid literals are written in decimal notation, the integer part is separated from the fractional point.

A real number can be written in floating point form , for example: 5.4e19, 17E-11, -123e + 4. That part of the number that stands before the letter e is called the mantissa, and the part that stands after the letter e is the order. Writing means the following: it is necessary to raise 10 to the power of order and multiply by the mantissa. Sometimes it’s really more convenient to write 1e-9 than 0.000000001.

Single characters are written in apostrophes, for example, 'a', 'D', '@'.

There are some special and control characters that are written using a special control sequence. The most common ones are listed in the table:

Control sequence Description
\ ddd Octal Character (ddd)
\ uxxxx Unicode hexadecimal character (xxxx)
\ ' Apostrophe
\ " Quotation mark
\\ Backslash
\ r Carriage return
\ n Line feed, new line
\ t Horizontal tab (tab)
\ b Return to character (backspace)

The control sequence also consists of apostrophes.

The first line of the table says that any character can be specified using its code (with decimal encoding from 0 to 255) by writing this code in octal notation. For example, the letter "g" in the coding CP1251 is written in the control sequence '\ 346'

If necessary, you can specify the code of any character in the Unicode encoding - after the backslash and the Latin letter u - with four hexadecimal characters. For example, '\ u0055' is the letter U.

Character strings are written in quotes. The opening and closing quotes must be in the same line of program code.

For rows, a clutch + operation is defined, which allows you to collect several rows into one ("attributing" them to each other).

If the string constant is too long and is poorly perceived in the program code when writing it into one line, you can write it into several lines, connecting them using string concatenation operation. For example:

"Это очень длинная строковая константа, записанная" + "на двух строках исходного текста"

Control characters and codes are written in the same line with the backslash (but without apostrophes).

Logical literals are true (true) and false (false).

Identifiers

about the rules of good style

The identifier is a name that is given to some program object: a variable, class, method, etc.

When programming, it is constantly necessary to invent identifiers for naming objects.

The identifier may consist of letters, numbers, an underscore _ and a dollar sign $ (the latter is not recommended, Java uses it for its own needs). The identifier cannot begin with a digit. Java keywords cannot be used as identifiers (as well as the literals true, false, and null ).

As noted above, the Java language distinguishes between simple and lowercase letters . This means that myAge , myage and MyAge are the names of completely different objects. Be careful: an error in the register - a very common case!

Choosing names is recommended to follow the following rules of good style.

Class names begin with a capital letter, if the name consists of several words, then each word begins with a capital letter. For example: MyClass , Book .

Method and variable names begin with lowercase (small letters); If the name contains several words, each next word begins with a capital letter. For example, myVar , x , y , newBigCounter .

The names of the constants are written in capital letters; if the name contains several words, an underscore is placed between them. For example, PI , COUNT_OF_MONTHS.

When using these recommendations you will get many benefits. One of them is that you will know exactly how to arrange upper and lower case letters when using standard Java libraries, the developers of which followed the recommendations.

Data types

about java data types

The most common type for storing integers in Java is int.

In general, there are four integer types in the Java language: byte, short, int, long. They differ in the amount of memory that will be allocated to a variable and, accordingly, the range of values ​​that can be stored in this variable. The most commonly used type int occupies 4 bytes in memory and is suitable for storing numbers from -2147483648 to 2147483647. The byte type consumes the least memory and is suitable for working with small numbers (from -128 to 127). The types short and long occupy 2 and 8 bytes respectively.

For real numbers, double is appropriate.

Real (real) numbers (or floating point numbers) are represented by two types: float and double. The float type takes 4 bytes of memory and does not provide a large degree of accuracy when working with very large or very small numbers. It is recommended to be used when the fractional part is needed, but high accuracy is not required (for example, to measure distances in meters, but taking into account centimeters and millimeters or measuring prices in rubles, taking into account kopecks). If more accurate calculations are needed, it is recommended to operate with double type values ​​(for example, such a variable can store the value of the sine of the angle).

Valid literals such as 5.3 , 8.0 , 2e-3 , Java considers to be of type double. If they are to be used in the program as float values, it is necessary to end them with the letter f : 5.3f , 8.0f , 2e-3f .

For storing single characters, the type is char. Java considers it a type of integer type (since each character is defined by its Unicode code), so all operations with integers are applicable to char.

Boolean values ​​(assuming true or false values) are represented by the type boolean.

Thus, in Java eight simple types are defined, the features of which are presented in the table:

Type of Size (bits) Minimum value Maximum value Description Default value
boolean - - - logical type false
char sixteen Unicode 0 Unicode 2 16 -1 character type '\ u0000'
byte eight -128 +127 signed integer 0
short sixteen -2 15 +2 15 -1 signed integer 0
int 32 -2 31 +2 31 -1 signed integer 0
long 64 -2 63 +2 63 -1 signed integer 0L
float 32 3.4e-038 3.4e + 038 real 0.0f
double 64 1.7e-308 1.7e + 308 real 0.0d

Variable declaration

In the Java language (as in many other languages) a variable is required to be described before using it. To describe a variable is to give it a name and determine its type.

When declaring a variable, you first specify the type (which may be one of the simple types, the name of the class or interface), then the identifier is the name of the variable. If the variable needs to be initialized (assign an initial value), the initial value is indicated after the name by an equal sign. A comma can be used to declare several more variables of the same type.

Examples of variable declarations:

int x; // Объявление целочисленной переменной x int x; // Объявление целочисленной переменной x double a, b; // Объявление двух вещественных переменных a и b double a, b; // Объявление двух вещественных переменных a и b char letter = 'Z'; // Объявление символьной переменной letter, инициализация начальным значением 'Z' char letter = 'Z'; // Объявление символьной переменной letter, инициализация начальным значением 'Z' boolean b1 = true, b2, b3 = false; // Объявление трех логических переменных, первая из них будет иметь значение true, последняя — false boolean b1 = true, b2, b3 = false; // Объявление трех логических переменных, первая из них будет иметь значение true, последняя — false

Basic language operations

Variables and literals can participate in operations (of which, in turn, complex expressions can be built). Consider the simplest operations of the Java language.

Mathematical operations

Operation Using Description
+ op1 + op2 Add op1 and op2
- op1 - op2 Subtracts op1 from op2
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Calculates the remainder of dividing op1 by op2

Comparison operations, the result is a boolean value: true (true) or false (false)

Operation Using Returns true (true) if
> op1 > op2 op1 more than op2
>= op1 >= op2 op1 is greater than or equal to op2
< op1 < op2 op1 less op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal

Logical operations

Operation Using Returns true (true) if
&& op1 && op2 op1 and op2 both truths (conjunction)
|| op1 || op2 one of op1 or op2 is true (disjunction)
! !op op - false (denial)
^ op1 ^ op2 op1 and op2 are different (exclusive or)
about java operations

Operations && and || differ in that they do not necessarily calculate the value of the second operand. For example, && calculates the value of the first operand and, if it is false, immediately returns false , and || returns true immediately if it sees that the first operand is true. In Java, there are operations similar to & | they compute the values ​​of both operands before performing an operation on them.

Shift operations

(work with the bit representation of the first operand)

Operation Using Description
>> op1 >> op2 shifts the op1 bits to the right by op2
<< op1 << op2 shifts the op1 bits to the left by op2
>>> op1 >>> op2 shifts the op1 bits to the right by op2 (excluding the sign)

Bit operations

(working with bitwise representation of operands)

Operation Using Description
& op1 & op2 bitwise and
| op1 | op2 bitwise or
^ op1 ^ op2 bitwise exclusive or
~ ~op2 bitwise complement

Operation ?:

Operation?: Ternary, that is, it has three operands. The first operand is a condition, an expression of a logical type. The second and third operands are expressions of any other type. The operation works as follows: if the condition is true, it returns its second operand as a result, and if false, the third one.

For example, the expression (5 > 3)? 7+1: 2*2 (5 > 3)? 7+1: 2*2 will have the value 8, and the expression (5 == 3)? 7+1: 2*2 (5 == 3)? 7+1: 2*2 - value 4. This entry does not look very clear, but programmers often use it to shorten their code. So, instead of a sequence of commands:

if (x > 0) y = 45 + a*2; // оператор if рассматривается ниже if (x > 0) y = 45 + a*2; // оператор if рассматривается ниже else y = 45 - b*3;

can write:

y = 45 + ((x > 0)? a*2: -b*3);

Assignment operator

After the variable is described, it is possible to work with it in the program. In particular, it can be assigned a value of the appropriate type. Then in the future, when using this variable in any expression, this current value will be automatically substituted for it.

The value is associated with a variable using an assignment operator. In Java, it is written with a simple equal sign:

переменная = выражение;

The variable to the left of the assignment operator is always specified. The expression on the right must match the variable by type. It can be just a literal (for example, a number or a character):

x = 7; // переменной x присваивается значение 7 x = 7; // переменной x присваивается значение 7 letter = 'Q'; // переменной letter присваивается значение 'Q' letter = 'Q'; // переменной letter присваивается значение 'Q'

In the general case, an expression is something that can be calculated (for example, the result of a mathematical operation or the result returned by some method):

a = 7.5 + 2.4; // переменной a присваивается 9.9 как результат вычислений

Along with literals, other variables can be included in the expression. Instead, their current value is substituted. As a result of the command:

b = a + 1;

the variable b will take the value 10.9.

So, the assignment operator acts as follows. First, the value of the expression on the right side is calculated, and then the result is assigned to the variable specified on the left side. Even the following situation is possible:

x = x + 4;

This command increases the current value of the integer variable x by 4.

And the following commands are written incorrectly and will not work:

5 = x + 7; // слева должна стоять переменная 5 = x + 7; // слева должна стоять переменная x + 3 = 14; // слева должна стоять просто одна переменная x + 3 = 14; // слева должна стоять просто одна переменная x = 4.5; // переменная x может принимать только целочисленные значения x = 4.5; // переменная x может принимать только целочисленные значения

Eclipse will attempt to point out an error in these lines even before the program is executed by placing warning signs in the margin of the code editor. You can see how he does it.

on casting

When a variable of one type is assigned a value of another type, coercion (conversion) of types is used . Для числовых типов (byte, short, int, long, float, double, char) оно происходит автоматически, если тип изменяемой переменной может "вместить" значение другого типа.

Например, если переменной типа int присвоить значение типа byte, автоматически произойдет преобразование типа byteв тип int. Аналогично тип float может быть приведен к типу double и т.п.

При попытке присвоить переменной менее точного типа (например, byte) значение более точного типа (например, int) компилятор выдаст сообщение об ошибке.

Для приведения типа можно использовать оператор приведения типа – перед выражением, для которого мы хотим выполнить приведение типа, ставятся круглые скобки с типом, к которому выполняется приведение, внутри скобок. При приведении целого типа большей точности к целому типу меньшей точности может быть выполнено деление по модулю на допустимый диапазон типа, к которому осуществляется приведение, а при приведении выражения типа double к выражению типа float будет уменьшена точность представления выражения.

long j = (long)1.0; //используем оператор приведения типа к long, j = 1 char ch = (char)1001; //используем оператор приведения типа к char, ch = 'd' byte b2 = (byte)(100); //используем оператор приведения типа от int к byte, b2 = 100 byte b3 = (byte)(100 * 2); //внимание! происходит деление по модулю, b3 = -56

Ошибка несовпадения типов часто возникает применительно к действительным литералам. Например, нельзя выполнить присваивание a = 7.5 + 2.4; , если переменная a имеет тип float, поскольку литералы 7.5 и 2.4 считаются относящимся к типу double. Чтобы не было ошибки, необходимо использовать приведение типов:

a = (float)(7.5 + 2.4);

или указать, что литералы также относятся к типу float:

a = 7.5f + 2.4f; // это тоже правильная команда

Практически для каждой бинарной операции существует своя разновидность оператора присваивания. Например, для операции сложения + существует унарный оператор присваивания += , который увеличивает значение операнда на заданную величину:

x += 8; // то же самое, что x = x + 8 (x увеличивается на 8)

Аналогично для других операций: операторы *= , -= , /= , %= , &= ^= и т.д:

x *= 3; // то же самое, что x = x * 3 (x увеличивается в 3 раза) b1 ^= b2; // то же самое, что b1 = b1 ^ b2

Exercise 1

Declare two integer variables, assign them any values. Print their sum and product.

Hint: you can use the project already created in Eclipse by inserting the necessary commands after the command to output the string "Hello, world!" either instead of her.

Increment and Decrement Operators

about increment and decrement operators

The increment and decrement operators ++and ––increase and decrease by one the value of the operand. It is much more convenient to use the command x++;instead of the command.x = x+1;

The increment and decrement operators also return a value. This means that it is legitimate to execute the command

y = 7 * x++;

As a result, the variable x will increase by 1, and the variable y will take a value seven times the old value of x. You can also execute the following command:

y = 7 * ++x;

В результате переменная x увеличится на 1, а переменная y примет значение, в семь раз большее нового значения x.

Условный оператор if

Простейшая форма записи условного оператора имеет вид:

if (условие) команда

Условие в скобках представляет собой логическое выражение, т.е. может быть истинным или ложным. Если условие окажется истинным, команда будет выполнена, в противном случае ничего не произойдет. For example:

if (x < 17) x = 17; // если значение переменной x меньше 17, x присвоить 17

Если же необходимо, чтобы в случае, когда условие ложно, была выполнена какая-то другая команда, используют расширенную форму оператора if:

if (условие) команда1 else команда2
о конструкции else if

В примере, рассмотренном выше, мы можем захотеть присвоить переменной x значение 5, если условие x < 17 не выполняется (зачем оно нам, другой вопрос).

if (x < 17) x = 17; else x = 5;

Если необходимо использовать несколько взаимоисключающих условий, их можно записать следующим образом:

if (условие1) команда1 else if (условие2) команда2 else if (условие3) команда3 ... else командаN

Exercise 2

Declare two integer variables, assign them any values. Using the if operator, find and output their maximum.

Hint: the algorithm for finding the maximum was considered above when repeating the basic constructs of the algorithm.

Composite teams

Multiple Java commands can be combined into one compound command using curly brackets {}. For example, you can write:

{ a = 12; letter = 'D'; }

Composite commands can be used wherever they are normal. For example, in an if statement, if, when a condition is met, several actions must be performed:

if (x < 17) { x = 17; letter = 'S'; } else { x = 5; }

The construction of curly brackets is also called a command block , and curly brackets are called block boundaries .

Заметим, что используемая в примере форма записи (когда границы блока размещаются на отдельных строках, а содержимое блока записывается с отступом от его границ), не обязательна. Это просто правило стиля, позволяющее сделать программы более понятными и не запутаться в фигурных скобках, которые в программе на Java приходится использовать довольно часто.

об операторе выбора switch

Оператор выбора switch

Часто выбор команды, которую необходимо выполнить, зависит от значения некоторой переменной (или выражения). Например, пользователю предлагается ввести знак операции и в зависимости от введенного символа требуется вывести на экран результат сложения, вычитания и т.п. или, если введен неправильные знак, сообщение об ошибке. В этом случае удобно использовать оператор выбора switch, имеющий следующую форму записи:

switch (выражение) { case значение1: последовательность команд 1 break; case значение2: последовательность команд 2 break; ... default: последовательность команд по умолчанию }

Значение1, значение2 и т.д. — это константы или выражения, в которых участвуют только константы. Выражение в скобках после ключевого слова switch может содержать переменные. Это выражение вычисляется, а затем ищется соответствие результата с одним из значений после ключевого слова case. Если такое соответствие найдено, то выполняется вся последовательность команд, расположенная между двоеточием и ближайшей командой break. Если не найдено ни одного соответствия, выполнится последовательность команд по умолчанию, стоящая после ключевого словаdefault. For example:

char oper; // Знак операции, его выберет пользователь ... // Будем считать, что к этому моменту пользователь выбрал знак switch (oper) { case '+': System.out.println(a + b); break; case '-': System.out.println(a - b); break; case '*': System.out.println(a * b); break; default: System.out.println("Неверный знак операции"); }

Можно опустить раздел default. В этом случае если совпадение не будет найдено, не выполнится ни одна команда.

Оператор цикла while

Цикл while имеет следующую форму:

while (условие) команда

Если условие в скобках (представляющее собой логическое выражение типа boolean) истинно, будет выполнена команда — тело цикла (это может быть простая команда или последовательность команд в фигурных скобках), после чего программа снова вернется к выполнению этого оператора и будет повторять это до тех пор, пока условие не окажется ложным.

Следовательно, чтобы программа не вошла в бесконечный цикл и не зависла, в теле цикла должна предусматриваться возможность выхода, то есть, например, команды в теле цикла должны как-то влиять на переменные, входящие в условие.

К примеру, следующий фрагмент программы выводит четные числа от 2 до 10:

int x = 2; while (x <= 10){ System.out.println(x); x += 2; }
о цикле while с постусловием

Существует другой вариант записи цикла while:

do команда while (условие)

При использовании этого варианта сначала выполняется команда, а потом проверяется условие. Оба варианта работают одинаково, но во втором случае тело цикла (команда) выполнится хотя бы один раз, даже если условие изначально ложно.

Exercise 3

С помощью цикла while выведите все нечетные числа от 1 до 10.

Подсказка: немного измените алгоритм вывода четных чисел.

Оператор цикла for

Цикл for обычно используется, когда известно заранее сколько раз должно повториться выполнение команды (или последовательности команд). Он имеет следующую форму:

for (команда инициализации; условие; команда перехода) тело_цикла

Перед началом цикла выполняется команда инициализации. Затем проверяется условие перехода (представляющее собой логическое выражение). Если это условие истинно, выполняется команда (или блок команд в фигурных скобках), составляющая тело цикла. Затем выполняется команда перехода и все начинается заново. Команда перехода обычно изменяет переменную, влияющую на истинность условия, а команда инициализации представляет собой описание этой переменной.

Обычно цикл for используется в следующем виде:

for (int i = 1; i <= 10; i++) тело_цикла;

В этом примере тело_цикла выполнится ровно 10 раз. При этом на каждой итерации будет доступна переменная i (она называется переменной цикла), последовательно пробегающая значения от 1 до 10. Следующий фрагмент программы выводит четные числа от 2 до 10 (аналогично примеру цикла while):

for (int i = 1; i <= 5; i++) System.out.println(i*2);

Exercise 4

С помощью цикла for выведите все нечетные числа от 1 до 10.

Операторы break и continue

Когда тело цикла (for или while) состоит из нескольких команд, может возникнуть ситуация, что на очередной итерации выполнять их все нет необходимости. В этом случае полезными оказываются операторы break и continue.

Оператор break прекращает выполнение текущего цикла, независиом от того, выполняется ли условие его окончания.

Оператор continue прекращает выполнение текущей итерации цикла. То есть, если в теле цикла встречается этот оператор, то остальные, следующие за ним команды пропускаются и начинается новая итерация (повторение) цикла.


Conclusion

Несмотря на то, что материал первого занятия достаточно обширный, он не должен вызвать затруднений у студентов, уже знакомых хотя бы с одним языком программирования, поскольку конструкции во всех языках одни и те же и необходимо лишь освоить правила их записи (синтаксис). Если же знакомство с другими языкми программирования состоялось слабое, необходима усиленная домашняя работа над пособием и решение дополнительных задач. Наилучшим вариантом в этом случае будет прочтение до начала следующего занятия рекомендуемых глав из предложенной литературы.

additional literature

1. Вязовик Н.А. Программирование на Java. (главы 1 — 4, 7, 10)

2. Хабибуллин И.Ш. Самоучитель Java 2. (глава 1)

Обратите особенное внимание на типы данных Java и правила приведения типов, затронутые в данном пособии недостаточно подробно. Профессиональный программист всегда должен контролировать в своих программах возможность выхода значения переменной за допустимый для ее типа диапазон. Ошибки, связанные с приведением типов, одни из самых распространенных и труднообнаруживаемых. Главы 4 и 7 первой книги настоятельно рекомендуются к прочтению всем студентам, претендующим на отличную оценку.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

OOP and Practical JAVA

Terms: OOP and Practical JAVA