|
Conditional Statements - if-then-else
In all language (like English) conditional statements
are integral to functionality. If a condition is met then do something.
We also have if else statements where if something happens, do something,
else do something else.
A condition could be if something is
- true
- == this is for equals - DO NOT USE ONE EQUALS
- >=
- <=
- >
- <
- != this means not equals
if (condition is met)
{
//do this
}
else //we do not have to have an else statement)
{
//do this
}
int k = 250;
if (k==200)
{
display k is 200
}
else
{
display k is not 200
}
And and Or
- To use and we use the symbols: &&
- To use or we use the symbol || (which you will find above the enter key)
for example if we wanted two conditions to be met:
if (x>0 && x<25)
{
do this
}
We can bring multiple statements together
if ((x>0 && x<=5) || x>25)
{
do this
}
Strings
Strings are objects which makes == generally not
work. To check equality for Strings you will use the equals method.
So if you wanted to say
job=="worker"
it should be:
job.equals("worker")
So could block might look like:
if (job.equals("worker"))
payRate=6;
Else if statements
you can have multiple if statements together-
if (inputString.equals("cat"))
{
do this
}
else if (inputString.equals("dog"))
{
do this
}
else if (inputString.equals("fish"))
{
do this
}
else
{
//sorry i dont understand your pet
}
If you only have one command for your if statement, you do not
need brackets. The if statement will do the following command.
ie:
if (x>25 && x<50)
myTool="rectangle";
In bluej, create a class called Conditionals.
Lets create these methods:
|