if and else - Macon State College

Document Sample
if and else -  Macon State College Powered By Docstoc
					if and else

   Simple ‘if’
    if and else
    Nested ifs
 ifs with braces
             Three control structures
1.       Sequential – Statements one after the other
2.       Selection-Altering the flow of program execution by
         making a selection or choice
     –      Single: if
     –      Double: if…else
     –      Multiple: switch
3.       Looping - Altering the flow of program execution by
         repetition of statement(s)
     –      While
     –      Do…while
     –      for
Flow of Execution
           Relational Operators
• Allow comparisons that result in either ‘true’ or
  ‘false’
• Java relational operators:
   = = (equal)
   != (not equal)
   < (less than)
   <= (less than or equal)
   > (greater than)
   >= (greater than or equal)
               ‘if’ statement
• Basic syntax:
  if(expression)
      StatementToBeExecuted;

• Examples:
  if(x<y)
      x=x+1;
  if(cost>price)
      cost=a + b;
Simple if statement
                              ‘else’
• Format:
       if(expression)
               // do this
       else
               // do that
• If the expression evaluates to true
   – the statement immediately after the first part of the ‘if’ is executed
   – execution then continues after the statement after the ‘else’.
• If the expression evaluates to false
   – the statement immediately after the ‘else’ is executed.
   – execution then continues with the next statement.
• Semicolons go on the end of the statements that are after
  the ‘if’ and the ‘else’.
                             ‘else’
• Example:
      if(size<2)
        name=“small”;
      else
        name=“big”;
      System.out.print(name);
• If the size variable contains a 1
   – name is set equal to “small”
   – execution jumps to the statement that begins with “System.out…”
• If the size variable contains a 4
   – Name is set equal to “big”
   – Execution continues with the statement that begins with
     “System.out…”
                   ‘else’
The ‘false’ side
is the same as              The ‘true’ side
    the ‘else’               is the same
                              as the ‘if’
     Double Selection Example
• Create a program that prompts for
   – a number of donuts
   – a flavor of either ‘chocolate’ or ‘plain’.
• If the user picks chocolate, print the total
  cost calculated as number of donuts * .35.
• If the user picks ‘plain’, print the total cost
  as number of donuts * .25.
                     Donut ‘if’
….
int numberOfDonuts = myInput.nextInt();
String flavor = myInput.next();
if(flavor.equals(“chocolate”))
    System.out.printf(“Your donuts will cost %.2f“,
    numberOfDonuts *.35;
else
    System.out.printf(“Your donuts will cost %.2f“,
    numberOfDonuts *.25;
….
                          Nested if
• if statements can be nested inside of if statements
• Example
  if(expression)
      if(expression)
                 // do this
     else
                 // do that
   else
      if(expression)
                 // do something
      else
                 // do another thing
         Donut Example Nested
• Create a program that prompts for
   – a number of donuts
   – a flavor of either ‘chocolate’ or ‘plain’.
• If the user picks chocolate, print the total cost
  calculated as number of donuts * .35.
• If the user picks ‘plain’, print the total cost as
  number of donuts * .25.
• If the user picks neither, print “you entered an
  invalid flavor”
                            Donut ‘if’
….
int numberOfDonuts = myInput.nextInt();
double price=0.0;
String flavor = myInput.next();
if(flavor.equals(“chocolate”))
     System.out.printf(“Your donuts will cost %.2f“, numberOfDonuts *.35;
     else
     if(flavor.equals(“plain”))
            System.out.printf(“Your donuts will cost %.2f“, numberOfDonuts *.25;
            else
                      System.out.printf(“You entered an invalid flavor”);
….
              Grouping ifs
• Until now we’ve just had one statement that
  had to be executed as a result of an if or an
  else
• If more than one statement has to be
  executed, curly braces { } can be used to
  group statements.
             if’s and curly braces
• Consider the example of an if statement that should result
  in three statements being executed.
• If its written this way….
        if(expression)
                statement1;
                statement2;
                statement3;
• If the expression is true, what gets executed?
        All three
• If the expression is false, what gets executed?
        statement2 and statement3
            if’s and curly braces
• We can use curly braces to change the expression
  on the previous page so that all three execute only
  if the expression is true
• if(expression)
       {
       statement1;
       statement2;
                                         The end of this if
       statement3;                       statement is now
                                             where the
       }                                    closing curly
                                                brace is.
    Yet Another Donut Example
• Create a program that prompts for
   – a number of donuts
   – a flavor of either ‘chocolate’ or ‘plain’.
• If the user picks ‘chocolate’
   – print the total cost calculated as number of donuts * .35.
   – Set a variable to ‘brown’ to indicate the color of bag in which to
     put the donuts.
• If the user picks ‘plain’
   – print the total cost as number of donuts * .25.
   – Set a variable to ‘silver’ to indicate the color of bag in which to put
     the donuts.
• If the user picks neither, print “you entered an invalid
  flavor”
          Donuts with curly braces
if(flavor.equals("chocolate"))
{
     System.out.printf("Your donuts will cost %.2f", numberOfDonuts *.35);
     bag="brown";
}
     else
           if(flavor.equals("plain"))
           {
                      System.out.printf("Your donuts will cost %.2f",
                      numberOfDonuts *.25);
                      bag="silver";
           }
           else
                      System.out.print("Wrong");
     Beware the dangling ‘else’
• Consider this:
  if(username.equals(“liz”))
        if(password.equals(“riley”))
                System.out.println(“Correct”);
        else
                System.out.println(“Wrong”);
• If username is equal to “liz” and password is equal
  to “riley”, what happens?
   – “Correct” displays on the screen
• If username is equal to “liz” and password is equal
  to “bob”, what happens?
   – “Wrong” displays on the screen
     Beware the dangling ‘else’
• Keep looking at this:
  if(username.equals(“liz”))
       if(password.equals(“riley”))
              System.out.println(“Correct”);
       else
              System.out.println(“Wrong”);
• If username is equal to “bob” and password is
  equal to “sam” what happens?
   – Nothing
   – Hummm….that’s probably not what was intended to
     happen…
       Beware the dangling ‘else’
• The rule for ‘dangling elses’:
    – ‘else’ is associated with the last ‘if’ that doesn’t
      already have an ‘else’

if(username.equals(“liz”))
         if(password.equals(“riley”))
                 System.out.println(“Correct”);   This if and else
         else                                     are associated.
                 System.out.println(“Wrong”);

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:0
posted:3/13/2012
language:
pages:22