JMU
Conditions and Decisions
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Motivation
Two Conditional Statements in Java
The switch Statement
The switch Statement (cont.)

An Example

javaexamples/basics/SwitchExample.java (Fragment: 0)
       switch (seatLocationCode)
       {
          case 100:
             vip   = true;
             price = 40.0;
             break;
                
          case 200:
             price = 30.0;
             break;
                
          case 300:
             price = 15.0;
             break;
                
          default:
             price = 0.0;
             break;
       }
        
The if Statement
The if Statement (cont.)
Best Practices Involving if Statements
Eliminating Empty if Clauses
Defaults in if Statements
Styles of if Statements
Nested if Statements

The statement Can Be Another if

javaexamples/basics/IfExample2.java (Fragment: 0)
       if (income < 30000) 
       {
          level = "Low";
       }
       else
       {
          if (income < 60000) 
          {
             level = "Middle";
          }
          else
          {
             level = "High";
          }
       }

        
Nested if Statements (cont.)

A Condensed Style for "Nesting"

javaexamples/basics/IfExample2.java (Fragment: 1)
       if      (income < 30000) level = "Low";
       else if (income < 60000) level = "Middle";
       else                     level = "High";

        
Nested if Statements (cont.)

Multiple Nested if Statements

javaexamples/basics/IfExample3.java (Fragment: 1)
       if (years <= 1)
       {
          title = "Freshman";
       }
       else
       {
          if  (years <= 2) 
          {
             title = "Sophomore";
          }
          else 
          {
             if  (years <= 3) 
             {
                title = "Junior";
             }
             else 
             {
                title = "Senior";
             }
          }
       }

        
Nested if Statements (cont.)

A Condensed Style for Multiple Nested ifs

javaexamples/basics/IfExample3.java (Fragment: 0)
       if (years <= 1) title = "Freshman";
       else if  (years <= 2) title = "Sophomore";
       else if  (years <= 3) title = "Junior";
       else title = "Senior";
        
        
Nested if Statements (cont.)

A switch-Like Style

javaexamples/basics/IfExample4.java (Fragment: 0)
       if        (seatLocationCode == 100)   // case 100:
       {
          vip   = true;
          price = 40.0;
       } 
       else if (seatLocationCode == 200)    // case 200:
       {
          price = 30.0;
       } 
       else if (seatLocationCode == 300)    // case 300:
       {
          price = 15.0;
       }
       else                                 // default:
       {
          price = 0.0;
       }
        
Java vs. Python - Important Differences
Java vs. Python - Important Differences (cont.)