Wednesday in
class
Be
sure you have read (and understand) Chapter 2
In lab tomorrow
• You will be asked to write simple Java programs that
select between two sets of statements
– The if statement
• The programs will be something like Exercises 2.15, 2.16, 2.24, 2.25 on page 78 and 79 in your text
Arithmetic in Java Little Quiz (Test
Yourself)
• What will Java’s order in evaluating this expression:
•
Y = a * b % c + d / e – f
•
It will evaluate left to right with operators of the
same precedence, all of which will be evaluated before any lower precedence
•
Multiplication/division/mod are the highest precedence
•
Addition/subtraction is next
•
Assignment is the lowest precedence
–
Write this as
Java code
•
C = (ab)2
•
Y = ab3 + c
Selection
Control structures--statements that control the flow
of execution
•
All programs can
be written in terms of three control structures
–
Sequence
structure
•
Executing statements sequentially
–
if (condition)--
selection structure
•
Condition is either true or false
•
Select between paths of execution
–
Loops -- repetition
structures
•
Execute a block of statements over and over
Selection statements
• Allows the program to select to
execute a certain series of statements, and not another set.
• It decides which series to select based on a condition that follows an if statement
•
if (this is true)
do this
else do this
• In parentheses is the conditional expression that decides which set of statements to execute
• The condition may change as the value of a variable
changes
Conditional expressions
•
Conditional
expressions are often called
Boolean expressions
– They evaluate to either true or false
• Form: (value) operator (value)
– The value can either be a variable or a constant
– Examples: X
<= Y; A > B;
• Values can be any data type, but must both be the same
data type
(Smith
< Adams)
Relational operators
These express a relationship that evaluates
to true or false
= =
means equal to;
!= means not equal to
>, <
>=, <=
Selection statements in Java
• Two forms of the if statement
•
if (Boolean expression)
do something;
• OR
if (Boolean
expression)
do one thing;
else do something
different;
Example program
import
java.io.*;
public
class TryThis
{
public
static void main(String[ ] args)
{ int num1 = 4, num2 = 5;
if
(num1 > num2)
{
System.out.println(num1 +" is greater than " +
num2);
}
else
{ System.out.println(num2 +" is greater than " +
num1) ; }
}
}
The example modified
Import java.util.Scanner
public
class TryThis
{ public
static void main(String[] args) throws Exception
{ Scanner in = new Scanner(System.in);
int
num1, num2;
System.out.println("Please
enter two integers");
num1 = in.nextInt();
num2 = in.nextInt();
if
(num1 > num2)
System.out.println(num1 +" is greater than " +
num2);
else
System.out.println(num2 +" is greater than " + num1);
}
}