email me at borlaj@portlandschools.org
notes previous (09/07/06) submit the dump links  
 

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
    • if (lightOn)
  • == 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:

  • Create a method using the scanner class called public void classifyAvg() that will ask the user for their gpa and will spit out a,b,c,d,f.
  • Start with this method header public void lifeLeft(String gender, int age)
    • create a method called lifeLeft that will take in a gender [male, or female] and an age as a parameter and say how many years you have left to live. A women can expect to live 82 yrs and a man 79. So if they put in man,33 ; it would say 46 years left till you die.
  • Start with the method header: public void guessingGameUsing the scanner class; In this method you will have a magic number already set between 1 and 5 (see below). The person will have to guess the number. If they guess too high it will say too high, and if they guess too low it will say too low. If they guess it, they will say good guess.
     
    //the following code will give a random int between 1 and 5
    final int MAGICNUMBER=(int)(Math.random()*5+1)