cse 114 – computer science i conditional statements quirpon island, newfoundland
TRANSCRIPT
CSE 114 – Computer Science I
Conditional Statements
Quirpon Island, Newfoundland
• Take two data values of the same type
• Returns a boolean result (true or false)< (less than)> (greater than)<= (less than or equal to)>= (greater than or equal to)== (equal to)!= (not equal to)
• Examples:
Relational Operators
// result is true
// result is true
// result is false
result = (5 <= 9);
result = (3.9 > 3.19);
result = (’a’ == ’A’);
boolean result;
We will use these to build boolean expressions
Logical Operators• Two data values of type boolean
• Return a boolean result (true or false)– && (logical AND) , & (bitwise AND)– || (logical OR) , | (bitwise OR)
// result is false
// result is true
// result is falseresult = (5<=9 && 8>9);
result = (5<=9 || 8>9);
boolean result;
result = !(5<=9);
• Unary logical operator: ! (NOT)
We will not use these operators
Fully Parenthesize your Expressions
• What is the value of result after the assignment expression:
boolean result;
result = 5+x<7&&y/z==0; // confusing
• Answer: I don’t care because I would never write it that way
result = ( ( (5+x)<7 ) && ((y/z)==0) ); // better
The if…else if…else statement
• Used for program decision making
• if would test for first choice• else ifs would test for additional choices
– not required
• else would be for all other cases– not required
• Can you think of any decisions a program makes?
How do we use it?• Use either:
• You may also mix them:
if (boolean expression)
statement;
else if
(boolean expression2)
{
statement;
statement;
}
else
statement;
if (boolean expression)
{
statement;
statement;
}
if (boolean expression)
statement;
• Or:
Want to be safe? Always use bracketsif (boolean expression)
{
statement(s);
}
else if (boolean expression2)
{
statement(s);
}
else
{
statement(s);
}
Example using bracketsScanner keyboard = new Scanner(System.in);
System.out.print("Enter your systolic blood pressure: ");
int systolicBP = keyboard.nextInt();
if (systolicBP >= 120)
{
System.out.println("That's high");
}
else if (systolicBP >= 90)
{
System.out.println("That's normal");
}
else
{
System.out.println("That's low");
}
What’s wrong here?Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your systolic blood pressure: ");
int systolicBP = keyboard.nextInt();
if (systolicBP >= 120)
{
System.out.println("That's high");
}
if (systolicBP >= 90)
{
System.out.println("That's normal");
}
else
{
System.out.println("That's low");
}
Another Example Usage
PrintStream out = System.out;
out.print("Enter your total cholesterol level: ");
int totalCholesterol = keyboard.nextInt();
if (totalCholesterol >= 200)
{
out.println("You need to lower that");
out.println("Your cholesterol is too high");
}
else
out.println("Good, eat away!");
What’s wrong here?
PrintStream out = System.out;
out.print("Enter your total cholesterol level: ");
int totalCholesterol = keyboard.nextInt();
if (totalCholesterol >= 200)
out.println("You need to lower that");
out.println("Your cholesterol is too high");
else
out.println("Good, eat away!");
Why is this worse?
PrintStream out = System.out;
out.print("Enter your total cholesterol level: ");
int totalCholesterol = keyboard.nextInt();
if (totalCholesterol >= 200)
out.println("You need to lower that");
out.println("Your cholesterol is too high");
Comparing Strings
• Don’t use ‘==’ to compare Strings
• Why?– it compares their memory addresses
• Instead use the equals method
‘==’ bug example
• What’s the output?
String word = new String("Hello");
if (word == "Hello")
{
System.out.println(true);
}
else
{
System.out.println(false);
}
false
equals method example
• What’s the output?
String word = new String("Hello");
if (word.equals("Hello"))
{
System.out.println(true);
}
else
{
System.out.println(false);
}
true
Nesting if statements
• We can put if statements inside other if statements
• Why?– decision trees– some actions are dependent upon multiple conditions– many paths through a program
Nesting if statements exampleSystem.out.print("Enter an integer from 1 - 99: ");
int number = keyboard.nextInt();
if ((number >= 1) && (number <= 99)) {
if (number > 66) {
System.out.println("Top Third");
} else if (number > 33) {
System.out.println("Middle Third");
} else {
System.out.println("Bottom Third");
}
} else {
System.out.println("Illegal number"); System.out.println("Closing program!"); System.exit(0);
}
Coin Change Example RevisitedSystem.out.print("Input change amount (1-99):");originalAmount = scanner.readInt();if (originalAmount < 1 || originalAmount > 99)
System.out.println("ERROR: Out of range.");else {
numQuarters = originalAmount / 25;remainder = originalAmount % 25;numDimes = remainder / 10;remainder = remainder % 10;numNickels = remainder / 5;numPennies = remainder % 5;if (numQuarters != 0)
System.out.println(numQuarters + " quarters");if (numDimes != 0)
System.out.println(numDimes + " dimes");if (numNickels != 0)
System.out.println(numNickels + " nickels");if (numPennies != 0)
System.out.println(numPennies + " pennies");}
Example (cont’d)
• Another way to print out coin information which looks even better!
• ORIGINAL WAYif (numQuarters != 0)
System.out.println(numQuarters+" quarters");
• NEW WAYif (numQuarters != 0)
{
System.out.print(numQuarters + " quarter");
if (numQuarters == 1)
System.out.println();
else
System.out.println("s");
}
The switch Statement• Used for multiway branches• EXAMPLE:int monthNum, daysInMonth;System.out.print("Input # of month(1-12): ");monthNum = scanner.readInt();switch (monthNum){ case 2: daysInMonth = 28;
break;case 4:case 6:case 9:case 11:
daysInMonth = 30;break;
default:daysInMonth = 31;
}
}Must list each value separately
For all other values
What happens if we leave out this break?
Must be integer or character variable
Can be an integer or character literal (like ‘4’), a variable, or a constant.
•Switch statement deficiencies:•Only integers and character can be used
•No ranges for cases