|
True or False?
Many of the decisions we make are based on true or false situations
- questions which require Yes/No answers. You might ask if two add two
is four, and get the answer YES or TRUE. Statements can be true or false
also:
-
This blue sheet of paper is red - FALSE
-
My dog has wings - FALSE
-
All positive integers are greater than -1 - TRUE
-
Java is cool - TRUE (naturally)
We can also base decisions on these TRUE or FALSE statements. For example,
we might say - "IF it's raining outside THEN take an umbrella with you
OTHERWISE leave the umbrella at home"
This is equivalent to saying if (raining outside = true) - Take Umbrella,
else Leave umbrella at home
Consider the third statement above - "All positive integers are greater
then -1". We could go on to say that "If a number is greater than zero
it is positive, and if it is less than zero it is negative".
This is just: if (number > 0) number is positive, else if (number <
0) number is negative.
What if?
Look at this code snippet:
int x = 20;
if (x > 10) System.out.println("The variable
x is greater than 10");
The program will only print out the message if our variable is greater
than 10. In fact, the expression in the brackets after "if" is a boolean
expression like we had before. It's a statement which is either true or
false. In the case above it is true.
int y = 0;
if (y > 5) System.out.println("The variable
y is greater than 5");
Here the statement in the brackets is false, so the command to print
out the message is not executed. Any Java expression which returns true
or false can be put in the brackets of an "if" statement.
int z = 100;
if (z > 10) System.out.println("The variable
z is greater than 10");
System.out.println("So z is quite big");
The above code will print out the first message if z is greater than
10. What about the second message though? This will be printed whatever
the value of z is, as it's outside the "if" instruction block.
The technique we've used so far only allows one command after the "if"
statement, but what is we want to execute a few commands like above? This
is where we can enclose our command in braces { }
So the above would become:
int z = 100;
if (z > 10)
{
System.out.println("The
variable z is greater than 10");
System.out.prinltn("So
z is quite big");
}
Now the code block will only be executed if the "if" expression evaluates
to true. Notice the indentation used. This is just a style convention,
and is completely ignored by the Java compiler. Good use of indention,
though, can make your programs much more readable and consequently easier
to debug, so it's a good idea to get into the habit now.
On the other hand...
Often in programming the above sort of statements it become necessary
to define what happens if the "if" statement is false. For example, you
might want one set of instructions to be executed if a result is true,
and another set to be executed if the result is false. So look at the following:
int x = 10;
if (x > 10)
{
System.out.println("The
variable x is greater than 10");
}
else
{
System.out.println("The
variable x is not greater than 10");
}
That was relatively painless, eh? As we only executed on command though,
we could have left out the braces, giving:
int x = 10;
if (x > 10) System.out.println("The variable
x is greater than 10");
else System.out.println("The variable
x is not greater than 10");
The result though is exactly the same. An "else" must follow an "if"
- it wouldn't make any sense otherwise would it?
If you think about it, you should be able to see where these "if" statements
are being used by other programmers. Think of when you try to quit out
of a word processor without saving your work. Normally a dialogue box appears
asking you if you want to save your work. So
if (work saved) quit;
else
{
ask user if they want
to save their work;
if (user clicks "yes")
{
save work;
quit;
}
else if (user clicks
"no") quit;
else return to the program;
}
This simplified "psuedo-code" shows how a quit dialogue might be arranged.
Firstly, the program will immediately quit if the work has been saved,
which is dealt with by the first line above.
If the work is not saved we enter the code block after the "else".
The first thing that will happen in this block is a window will appear
asking whether the user wants to save their work. This usually has three
buttons - a "yes", "no" and a "cancel" button.
The first case we deal with is if a user clicks "yes". Here we just
save the work then quit.
We then get to an "else if" statement if the user hasn't clicked "yes".
This is the same as a usual "else" statement but it has a condition that
must be met if the code after it is to be executed. Here we check to see
whether the user has clicked "no". If they have, we just quit. If they
haven't clicked "no", however, we move onto the next else statement. The
else refers to the previous "if" - in this case the "if (user clicked "no")"
case. So as the user hasn't clicked no, and we know the user hasn't clicked
"yes" or we wouldn't even be in this code block, the user must have pressed
"cancel". Thus we return to the program.
Er, Pseudo-code?
When I say psuedo-code, I mean code that isn't real - it cannot be run
by Java. It can be useful, however, when designing software. Often you
can be unsure of how a particular part of your code will be implemented,
and so a brief sentence on what your program should do at that point can
be really useful. In the code above I have commands such as "save work"
and ' user clicks "yes" '. These aren't actual commands, but brief
descriptions of what the program should be doing at those particular points.
When you're in the design stage of software (i.e.. before you
actually program it) you'll often find yourself describing what your software
should be doing rather than how your software should do it. Designing software
in this way - like the pseudo code above, means different parts of the
software can be allocated to different programmers who have different skills.
Everyone will be able to understand what the pseudo code is aiming to do,
but not everyone will be too sure of how to actually implement every function.
Boolean Algebra and Truth Tables
It is often the case that we want to check if two things are true at
the same time, or one is true and the other false etc.
|
Logical Operator
|
In English |
Description |
|
&&
|
And |
Tests if two things are true. For example if ( (x>0) && (y>10)
) means literally "if x is greater than zero and y is greater than
10". If either of the expressions is false the entire "if" expression evaluates
to false. |
|
||
|
Or |
Tests if either of two things is true. So if ( (x>0) || (y>10) ) means
"if x is greater than zero or y is greater than 10". The "if" expression
will evaluate to true if either of the expressions is true. It will only
be false if both expressions are false. |
|
!
|
Not |
Whereas "&&" and "||" require two expressions to evaluate,
Not, !, requires just one. In Java, if (! (x>0) ) reads "if not (x>0)"
and means "if x is not greater than 0". Basically, "not" takes an
expression, and if the expression returns true, "not" will return false,
and vice versa. |
The following truth table shows what each operator will return given
different mixtures of true and false expressions as input:
|
A
|
B
|
A && B
|
A || B
|
!A
|
!B
|
|
True
|
True
|
True
|
True
|
False
|
False
|
|
True
|
False
|
False
|
True
|
False
|
True
|
|
False
|
True
|
False
|
True
|
True
|
False
|
|
False
|
False
|
False
|
False
|
True
|
True
|
So in the following code snippet:
int x=0;
int y=100;
if ( (x > 10) && (y > 10) ) System.out.println("Both
are greater than 10");
...we can see that if A is the first expression (x>10) and B is the
second expression (y>10), then A will evaluate to false and B will evaluate
to true. Checking in the above table at A && B when A is false
and B is true we see that (A && B) will return false - so our message
won't be printed. If we want the first expression (x>10) to return true
we could negate it - using "not" (!).
int x = 0;
int y = 100;
if ( !(x > 10) && (y > 10) )
System.out.println("The first isn't
greater than 10, the second is.");
This will work because "not false" is the same as "true" - so we end
up with "if (not(false) && true)", then "if (true && true),
which we have seen evaluates to true.
Checking Inequalities
When dealing with numbers it is often useful to know if one is larger
than the other, or if they're the same size etc. So how do we check whether
two numbers are equal? You might be tempted to say "if (a = b) command;"
You have to remember, though, that the "=" sign is the assignment operator
- it sets a variable to a value as in x = 5;
So in using "if (a = b)", what actually happens is that Java sets a
to the value that b is storing, and then returns true. You don't
need to know why it returns true, just that it isn't anything to do with
equality. What you want is the double equals - "==". So "if (a == b)" will
be the check you need to see whether the value stored in a is the same
as the value stored in b.
This table shows some other useful (in)equaltity checks:
|
Operator
|
In English |
Example |
Description |
|
>
|
greater than |
a>b
|
returns true if a is greater than b |
|
<
|
less than |
a
|
returns true if a is less than b |
|
>=
|
greater than or equal to |
a>=b
|
returns true if a is greater than or equal to b |
|
<=
|
less than or equal to |
a<=b
|
returns true if a is less than or equal to b |
|
==
|
equal to |
a==b
|
returns true if a is equal to b |
|
!=
|
not equal to |
a!=b
|
returns true if a is not equal to b |
So if you were to consider the following code snippet, it should read
just like english:
int x = 10, y = 20, z = 20;
if (x == y) System.out.println("x equals y");
else System.out.println("x doesn't equal y");
if (y == z) System.out.println("y equals z");
else System.out.println("y doesn't equal z");
So this is pretty straightforward stuff. Notice I've initialised three
integers on the first line. I could have done them separately as I have
before - with one on each line, but this method is more elegant. So:
int x=0,y=0,z=0;
is the same as:
int x=0;
int y=0;
int z=0;
You would have worked this out yourself, no? Anyway, the you should
see that the all these different equality checks aren't really necessary.
From what we've seen before, "if ( !(a == b) )" reads as "if a doesn't
equal b". Also, "if ( !(a > b) )" will read as "if a is not greater than
b", or rather "if a is less than or equal to b". So the only three you
really need are >, < and ==. One day you'll see why this fact can help
you.
Summary
If A, B, C etc. are boolean expressions (expressions which are either
true or false, such as x>10, y==0 etc.), the following control structures
can be used:
| Control Structure |
Description |
| if (A) command; |
command executed if A evaluates to true |
if (A)
{
command1;
command2;
} |
if A evaluates to true, all commands between
the braces will be executed in turn. |
if (A) command1;
else command2; |
command1 is executed if A is true. Otherwise
command2 is executed. |
if (A)
{
commands1;
}
else
{
commands2;
} |
commands1 are executed if the A is true, otherwise
commands2 are executed; |
if (A)
{
commands1;
}
else if (B)
{
commands2;
} |
commands1 executed if A is true. Otherwise, commands2
executed if B is true. Remember that B is only evaluated if A is
false. |
if (A)
{
commands1;
}
else if (B)
{
commands2;
}
else if (C)
{
commands3;
}
.
.
. |
commands1 are executed if A is true. Otherwise
commands2 are executed if B is true. Otherwise commands3 are executed if
C is true - and so on. As before, we only carry on through these "ifs"
if the previous if expression evaluated to false. Just one true if statements
and we execute the relevant commands then get out. |
if (A)
{
commands1;
}
else if (B)
{
commands2;
}
else if (C)
{
commands3;
}
.
.
.
else
{
commandsX;
} |
This is similar to the above, but notice the
else at the end.
This will ensure something will happen, because
if we haven't got out of these "else ifs" yet the else commands at the
end will be executed. |
Look at the following pseudo code. It's a program that thinks of a random
number and the user has to try and guess it. You should be able to follow
it through by now. Look at the "if" block. This block will check the user's
guess against the random number thought of, and display the relevant message.
Notice also that this psuedo code has a loop - between our first set of
braces the code is to be repeated until the "correct" flag is set to true.
The "correct" flag will only be set to true if the user enters the right
guess - as the "if" block will ensure. Whilst we haven't yet learnt enough
Java to implement all of this, the main part of the code (checking the
user's guess against the correct answer) is all dealt with by "if's".
think of a random number between 1 and 100 and
label it "x"
create a boolean variable (a variable that can
be true or false) and call it "correct"
Set "correct" to false
while our "correct" flag is set to false repeat
the following:
{
ask user for input
get user input and label
it as an integer called "guess"
if (guess > x)
System.out.println("Guess too high");
else if (guess <
x)
System.out.println("Guess too low");
else
{
System.out.println("Well done!");
correct = true;
}
}
Next month we'll look at how we can get our code to "loop" like we've
specified above, and we'll have a quick look at user input too so we can
fully implement the above as a Java application.
Exercises
-
What will the following expressions return (true or false) ?
-
(true) && (true || false)
-
(false) || (true && false)
-
!(true) && !(true || false)
-
!(true) || !(true || false)
-
!(10 > 3) || (0 == 0)
-
( (10 == 3) && ( 1 > 1 ) ) || (2 >= 2)
-
Write some psuedo-code (similar to "quit application" example earlier)
which first checks to see whether a given folder (directory) exists on
a users hard drive, and: (i) if it does then quit (ii) if it doesn't ask
the user if they want to create it. If the user does want to create it,
then create it then quit, otherwise just quit.
-
Write some psuedo-code (like before) that first checks whether a specified
file exists, and: (i) if it doesn't then display a message that says "file
not found" (ii) if it does then check whether it is an image file (for
example, with if (file is an image)...). If it's not an image file display
a suitable error message. Otherwise check whether the image is in JPEG
format. If not, ask the user whether they want to convert the image to
a JPEG. If they do then do the conversion then quit. Otherwise just quit.
Solutions to April's Exercises
-
The first thing I saw was a pen. Possible functions are:
-
Write (on some paper)
-
Change ink colour *(changes a property)
-
Tell me the pen colour (The pen has a colour so there must be something
telling me that)
-
Tell me the ink colour
Properties I thought of were:
-
Colour (of the pen)
-
InkColour (colour of the ink)
Okay, so maybe a pen wasn't that interesting...
-
These methods would need to be inserted into the class somewhere,
preferably near the setScreenWidth method.
public void setScreenHeight(int height)
{ screenHeight = height; }
public int getScreenHeight()
{ return screenHeight; }
-
Firstly insert the line ' String manufacturer = "Unknown"; ' into the variable
list at the beginning of the Monitor class. Then add the following two
methods:
public String getManufacturer()
{ return manufacturer; }
public void setManufacturer(String name)
{ manufacturer = name; }
-
Look at the initial list shown which describes many of the properties of
a monitor. Pick any of these you want to add to the class, thinking of
what datatype it should be. For example, if you add the "on/off" property
which defines whether the monitor is off or on, this could be provided
as a boolean value. So initially, on = true, indicating that the monitor
is on. Then later, if on = false this would indicate that the monitor was
off. So insert the line "boolean on = true;" to the variable list in the
monitor class. Then insert the methods:
public void turnMonitorOff()
{ on = false; }
public void turnMonitorOn()
{ on = true; }
public boolean isMonitorOn()
{ return on; }
The last method above will return true if the monitor is on,
and false otherwise.
-
My rendition of Abba's "Dancing Queen" was sadly not recognised.
|