Conditions in a programming language are instructions such as the further program flow. Similar to rail traffic. A that direct the flow of a program. This works a bit like rail traffic: a train travels on a rail until it hits a switch, then the train changes its direction of travel. The same applies to conditions in a program.
Conditions therefore change the course of a program. But according to which criteria is decided how the program process continueshow is the direction actually decided? The answer to this is logical operations based on the Boolean logic . Sounds more complicated than it is(remember the logic gates?) . We use logical operations in everyday life, here are some examples:
...
- equal to ==
- not equal !=
- greater than >
- less than <
- greater than or equal to >=
- less than or equal to <=
- logical And &&
- logical Or ||
In the code it looks like this looks as follows:
Code Block |
---|
int x = 10; if(x == 10) { println("x is the same as 10"); } else { println("x is not the same as 10"); } |
...
The syntax of a condition is always:
Code Block |
---|
if([boolischboolean expression]) { // blockcode derthat ausgeführtwill wirdbe wennexecuted derif boolischethe Ausdruckanswer Trueis isttrue } else { // blockcode derthat ausgeführtwill wirdbe wennexecuted derif boolischethe Ausdruckanswer Falseis istfalse } |
Of course there are also some variants of writing style:
Code Block |
---|
int x=10; // BedingungConditional ohne Klammer-Block, die Bedingung without brackets // gehtthe inconditional diesemwill Fallrun bisuntil zumthe nächstennext Semikolonsemicolon // dasThe "else" istis ebenfallsoptional optional if(x == 10) println("x ist gleich 10"); // HierHere is einea Bedinungconditional mitwith mehrerenmultiple Fällencases // zupay Beachtenattention istto diethe schreibweiseuse vonof 'else if' if(x == 10) println("x is istthe same gleichas 10"); else if(x == 9) println("x is the istsame gleichas 9"); else if(x == 8) println("x is istthe same gleichas 8"); else println("x istis nichtnot 10,9 oderor 8"); |
For the multiple cases, there is a simpler version:
Code Block |
---|
int x=10; switch(x) { case 10: println("x is istthe same gleichas 10"); break; case 9: println("x is the istsame gleichas 9"); break; case 8: println("x ist gleichis the same as 8"); break; default: println("x is the istsame nichtas 10,9 oderor 8"); break; |
Exercise
Programm a drawing program. The color can be changed with the buttons '1' - '5'. The left mouse button is draws and the right mouse button is used to erase it.