comp 110: introduction to programming
DESCRIPTION
COMP 110: Introduction to Programming. Tyler Johnson Feb 2, 2009 MWF 11:00AM-12:15PM Sitterson 014. Announcements. Program 1 due Wed by midnight Couple things. Questions?. Today in COMP 110. The type boolean switch statements Enumerations. Review. If-Statements - PowerPoint PPT PresentationTRANSCRIPT
COMP 110:Introduction to Programming
Tyler JohnsonFeb 2, 2009
MWF 11:00AM-12:15PMSitterson 014
COMP 110: Spring 20092
Announcements
Program 1 due Wed by midnightCouple things
COMP 110: Spring 20093
Questions?
COMP 110: Spring 20094
Today in COMP 110
The type boolean
switch statements
Enumerations
COMP 110: Spring 20095
Review
If-StatementsUsed to make decisions or check conditions in a program• E.g. check the value of a variable
Syntaxif(Boolean_Expression)
Statement_1else
Statement_2
If Boolean_Expression is true, Statement_1 is executed; otherwise Statement_2 is executed
COMP 110: Spring 20096
If Statement Exercise
What is the output?
if(x > 5) { System.out.print(‘A’); if(x < 10) System.out.print(‘B’);}else System.out.print(‘C’);
x Output
4 C
5 C
6 AB
9 AB
10 A
11 A
COMP 110: Spring 20097
Boolean Expressions
An expression that evaluates to either true or false
Consider ((x > 10) || (x < 100))Why is this probably not what the programmer intended?• It’s true for any x
Consider ((2 < 5) && (x < 100))Why is this probably not what the programmer intended?It’s the same as (x < 100)
COMP 110: Spring 20098
The Type boolean
boolean is a primitive type in JavaStores the value true or false
We can declare variables of type boolean just like we declare an int, double, etc.
boolean ready;boolean error;
COMP 110: Spring 20099
Booleans
Using booleans can make your programs easier to understand
//a bit difficult to readif(temp <= 100 && thrust >= 12000 && cabinPressure
> 30)System.out.println(“Launch”);
elseSystem.out.println(“Abort”);
COMP 110: Spring 200910
Booleans
Booleans can be used inside boolean expressions
boolean systemsGo = temp <= 100 && thrust >= 12000 && cabinPressure > 30;
//much easier to readif(systemsGo)
System.out.println(“Launch”);else
System.out.println(“Abort”);
COMP 110: Spring 200911
True and False
The words true and false are also reserved words in javaWe can use them to initialize boolean variables
boolean ready = false;boolean initialized = true;
COMP 110: Spring 200912
Booleans
There’s no need to write
if(systemsGo == true)System.out.println(“Launch”);
The more concise and equivalent way is
if(systemsGo)System.out.println(“Launch”);
COMP 110: Spring 200913
Naming Booleans
Choose names for boolean variables that sound true when the value of the variable is true
boolean ready; //are we ready?boolean readingInput; //are we reading input?boolean errorEncountered; //have we encountered //an error?
COMP 110: Spring 200914
Precedence
Java uses precedence rules when evaluating boolean expressions
Examplescore >= 80 && score < 90The expressions to the left and right of && are evaluated first
COMP 110: Spring 200915
Operator Precedence
Highest Precedence
First: the unary operators +, -, ++, --, !Second: the binary operators *, /, %Third: the binary operators +, -Fourth: the boolean operators <, >, >=, <=Fifth: the boolean operators ==, !=Sixth: the boolean operator &&Seventh: the boolean operator ||
Lowest Precedence
COMP 110: Spring 200916
Boolean Precedence Example
4 < 3 / 2 – 10 || 4 * -2 > 94 < 1 – 10 || 4 * -2 > 94 < 1 – 10 || -8 > 94 < -9 || -8 > 9false || -8 > 9false || falsefalse
COMP 110: Spring 200917
Style
It’s usually best to indicate precedence in boolean expressions explicitly with parentheses
(score < ((min / 2) – 10)) || (score > 90)
COMP 110: Spring 200918
Short-Circuit Evaluation
In some cases, the result of a boolean expression can be determined before all subparts of the expression are evaluated
Example
true || (x >= 60)
This expression is true regardless of the value of x
COMP 110: Spring 200919
Short-Circuit Evaluation
Java uses what’s called short-circuit evaluation when evaluating boolean expressions
If at any point in the evaluation of a boolean expression the outcome is determined, any remaining subparts are not evaluated
COMP 110: Spring 200920
Short-Circuit Evaluation
ExampleWe’re computing an average homework scorePrint “Good work!” if the average is above 60
if(numAssignments > 0 && ((total / numAssignments) > 60)System.out.println(“Good work!”);
Without short-circuit evaluation, we would divide by zero if numAssignments == 0
COMP 110: Spring 200921
Reading in Booleans
We can read in booleans from the keyboard just like any other variable
boolean bVar;Scanner keyboard = new Scanner(System.in);
bVar = keyboard.nextBoolean();
COMP 110: Spring 200922
Switch Statements
If-statements with many branches can be difficult to read
The switch statement can be used as an alternative to a multi-branch if-statement in certain cases
COMP 110: Spring 200923
Switch Statement
A switch statement begins like this
switch(Controlling_Expression) {
…
}
Controlling_Expression must have type int or char
COMP 110: Spring 200924
Switch Statements
Inside the body of a switch statement, a number of case labels will appear
The different cases are separated with a break statement
case Case_Label_1:Statements_1break;…
case Case_Label_n:Statements_nbreak;
COMP 110: Spring 200925
Switch Statement Example
int year;…switch(year) {
case 1: System.out.println(“You are a freshman”); break;
case 2: System.out.println(“You are a sophomore”);
break;case 3: System.out.println(“You are a junior”);
break;case 4: System.out.println(“You are a senior”); break;default: System.out.println(“This is a default case”); break;
}
COMP 110: Spring 200926
Switch Statement Example
int year = 1;…switch(year) {
case 1: System.out.println(“You are a freshman”); break;
case 2: System.out.println(“You are a sophomore”);
break;case 3: System.out.println(“You are a junior”);
break;case 4: System.out.println(“You are a senior”); break;default: System.out.println(“This is a default case”); break;
}
COMP 110: Spring 200927
Switch Statement Example
int year = 3;…switch(year) {
case 1: System.out.println(“You are a freshman”); break;
case 2: System.out.println(“You are a sophomore”);
break;case 3: System.out.println(“You are a junior”);
break;case 4: System.out.println(“You are a senior”); break;default: System.out.println(“This is a default case”); break;
}
COMP 110: Spring 200928
Switch Statement Syntax
switch(Controlling_Expression) {case Case_Label: Statements break;case Case_Label : Statements break;…default: Statements break;
}
COMP 110: Spring 200929
Switch Statements
If no break statement is specified, for a case, execution will continue down to the next case int n;…switch(n) {
case 1: System.out.println(“one”);case 2: System.out.println(“two”); break;
}
If n == 1, this code prints onetwo
COMP 110: Spring 200930
Switch Statement Example
char input;…switch(input) {
case 'y':case 'Y':
System.out.println(“You entered yes”); break;
case 'n':case 'N': System.out.println(“You entered no”);
break;default: System.out.println(“Invalid input”); break;
}
COMP 110: Spring 200931
Default Case
When using a switch statement you should always provide a default case
This catches any conditions you may not have checked for, such as errors
default:System.out.println(“This is a default case”);break;
COMP 110: Spring 200932
Conversion to If
The previous example can also be written equivalently with an if-statement
if(input == 'y' || input == 'Y')System.out.println(“You entered yes”);
else if(input == 'n' || input == 'N')System.out.println(“You entered no”);
elseSystem.out.println(“Invalid input”);
COMP 110: Spring 200933
If/Switch
How to know whether to use a switch or an if-statement?
Switch statementCan only be used with type char or intWhen you want to choose between many, specific values such as 5,6, 'y' etc.
If statementCan only be used with boolean expressionsWhen the number of choices is relatively smallWhen you want to check a range of possibilities, e.g. x > 5, y <= 1000
COMP 110: Spring 200934
Enumerations
Suppose you wanted to write a computer program that stores different flavors of ice cream
Vanilla, Chocolate, Strawberry, etc.
How would we store them in a computer program?
COMP 110: Spring 200935
Enumerations
We can give the flavors an underlying numeric representation
Vanilla = 0, Chocolate = 1, Strawberry = 2
We could declare a variable integer to store our flavor, but this is error-prone
int flavor = 0; //vanillaflavor = 1; //chocolate
COMP 110: Spring 200936
Enumerations
An enumeration allows us to give unique numeric values to a list of items
enum Flavor {Vanilla, Chocolate, Strawberry}
This statement assigns a unique numeric value to each of {Vanilla, Chocolate, Strawberry}
COMP 110: Spring 200937
Switch/Enum Example
enum Flavor {Vanilla, Chocolate, Strawberry}
Flavor flavor; //declare a variable of type Flavor…switch(flavor) {
case Vanilla: System.out.println(“That’s Vanilla!”); break;case Chocolate: System.out.println(“That’s Chocolate!”); break;case Strawberry: System.out.println(“That’s Strawberry!”); break;default: System.out.println(“I don’t recognize that flavor”); break;
}
COMP 110: Spring 200938
Programming Demo
Write a program that takes two numbers as input from the user
The user should then be able to choose from among the following options
Add the two numbersSubtract the two numbersMultiply the two numbersDivide the two numbers
COMP 110: Spring 200939
Programming Demo
PseudocodeAsk user to input two numbersProvide the user with a list of the optionsPerform the operation selected by the userOutput the result
COMP 110: Spring 200940
Programming Demo
Programming
COMP 110: Spring 200941
Wednesday
Loops
Keep up with the readingWe’ll start Ch 4 on Wed