Conditionals and Boolean Expressions - PowerPoint PPT Presentation

1 / 14
About This Presentation
Title:

Conditionals and Boolean Expressions

Description:

The basic idea of conditionals is to allow the behavior of a program ... this will usually be input of some kind. The conditional construct is extremely simple ... – PowerPoint PPT presentation

Number of Views:50
Avg rating:3.0/5.0
Slides: 15
Provided by: Steve57
Category:

less

Transcript and Presenter's Notes

Title: Conditionals and Boolean Expressions


1
Conditionals and Boolean Expressions
  • The basic idea of conditionals is to allow the
    behavior of a program to depend on value unknown
    at compilation time
  • this will usually be input of some kind
  • The conditional construct is extremely simple
  • A trivial variation

if (boolean-expression) execute-if-true
else execute-if-false
if (boolean-expression) execute-if-true
else
if (boolean-expression) execute-if-true

2
Simple Examples of Conditionals
Scanner sc new Scanner(System.in) double
salary sc.nextDouble() if (salary gt 50000.0)
System.out.println("You're rich!")
else System.out.println("Maybe it\'s time to
ask for a raise.")
Scanner sc new Scanner(System.in) // What
happens if the input isn't a double at
all? double salary sc.nextDouble() if (salary
lt 0.0) System.out.println("Invalid salary
value " salary) System.exit(1)
System.out.println("Your salary is " salary)
3
A Dirty Secret About Conditionals That We Will
Mention Once and Never Speak Of Again
  • The form we just saw introduces a block
    (multiple-statement block) that allows you to
    execute multiple statements in the true and/or
    false blocks
  • The alternative form allows only a single
    statement in each case

if (boolean-expression) statement1
statement2 else statement3
statement4 statement5
if (boolean-expression) statement1 else
statement2
4
More on Statements versus Blocks
  • Although the book introduces the single-statement
    form as the more fundamental (as it is), it is
    never to be used or even spoken of again!
  • The reasons are
  • you should not have two syntactic forms that do
    essentially the same thing
  • it leads to serious logic problems if youre not
    careful when you add statements to the code

if (temperature gt 100) System.out.println(Im
hot!) System.out.println(And another thing)
if (temperature gt 100) System.out.println(Im
hot!) System.out.println(But youre
not!) System.out.println(And another thing)
5
The One True Way
if (temperature gt 100) System.out.println(Im
hot!) System.out.println(And another
thing)
if (temperature gt 100) System.out.println(Im
hot!) System.out.println(But youre
not!) System.out.println(And another
thing)
6
Boolean (aka Logical) Expressions
  • The real question is how we get Boolean
    expressions in our programs?
  • the boolean constants true and false
  • relational operators (equals, less than or
    equals)
  • other methods that return boolean values
    (aScanner.hasNextInt())
  • Here is a very easy but very uninteresting
    conditional program. (Many compilers will notice
    that the else branch can never be executed, and
    will either warn you, remove the branch, or
    signal an error.)

public static void main(String args) if
(true) System.out.println("This is going
to happen!") else
System.out.println("This is never going to
happen!")
7
Relational Operators and the Primitive Types
  • Some data types are comparable any two
    instances can be compared with one instance being
    less than, equal to, or greater than the other
  • this is pretty obvious for numbers if x and y
    are numbers, you can use (x lt y), (x y), (x gt
    y)
  • you also get (x lt y) and (x gt y) and (x ! y)
    for convenience
  • these are the numeric relational operators
  • Characters (char) is also numeric and the same
    operators can be used (a lt b) (a lt A)
    (b B) (z lt \t)
  • Which of these are true? How would you find out?
  • Boolean (boolean) is not numeric, and there is no
    sense in which true is less than or greater than
    false
  • you can compare two boolean values using
    however
  • but you never want to because these two forms are
    equivalent
  • (aBoolean true) is equvalent to (aBoolean)
  • (aBoolean false) is equivalent to (!aBoolean)

8
Comparing Non-Primitive Data Types
  • Some Java-defined and user-defined data types can
    be compared some can not
  • Strings can be compared. It makes sense to say
    that one String is less than, equal to, or
    greater than another String. In fact thats how
    we talk about putting lists of Strings in
    alphabetical order.
  • Scanners cannot be compared. It does not makes
    sense to say that one Scanner is less than, equal
    to, or greater than, another Scanner. It does
    not make sense to talk about putting a list of
    Scanners in order.
  • Employee might or might not be comparable (your
    choice as designer). It might make sense to say
    one employee is less than another if his
    employee ID number is less than another. That
    defines a way to put a list of Employees in
    order.
  • PlayingCard would probably be comparable. How
    would we define what it means for one PlayingCard
    to be less than another?
  • Being comparable is something that the designer
    of the class has to build in, if it makes sense
    to do so at all
  • In any event, you do not use the relational
    operators to compare two non-primitive objects!

9
Equality and Non-Primitive Data Types
  • In any event, you do not use the relational
    operators to compare two non-primitive objects!
  • What is wrong with this program?

public static void main(String args)
Scanner s new Scanner(System.in) String
string1, string2 System.out.print("Give me a
string! ") string1 s.nextLine()
System.out.print("Give me another string! ")
string2 s.nextLine() if (string1
string2) System.out.println("Your two
strings are equal!")
10
Equality and the Non-Primitive Types
  • This is correct because interaction with
    non-primitive data types is done via method calls
    (String.equals(String)) rather than via primitive
    operators ()

public static void main(String args)
Scanner s new Scanner(System.in) String
string1, string2 System.out.print("Give me a
string! ") string1 s.nextLine()
System.out.print("Give me another string! ")
string2 s.nextLine() if
(string1.equals(string2))
System.out.println("Your two strings are the
same!")
11
Some Examples Using Conditionals
  • We want to explore the two main reasons
    conditionals are introduced into a program
  • Validating input
  • Computation that depends on input values
  • Input Validation
  • Accept a number from the console, and print it
  • Accept a positive number from the console, and
    print it
  • Read a value either less than 0 or greater than
    100 from the console, and print it
  • Read two numbers from the console, print their sum

12
More Examples
  • Conditional computation
  • Read a temperature (a number between -100.0 and
    500.0). Print youre freezing or youre
    getting warm or youre getting hot or youre
    cooking depending on the temperature
  • Read three numbers from the console and print the
    maximum
  • Read a number from the console. Then read a line
    that is either
  • a number
  • s number
  • n
  • and print either the sum or difference of the two
    numbers, or the negation of the first number

13
The Switch Statement
  • Useful if you have an object that takes on one
    from a fairly small set of values, and you want
    to do something different depending on that value
  • a nested if/then/else will work fine for this,
    but the nesting can get ugly

int firstValue 5 int finalValue char command
((String)stdinScanner.next()).charAt(0) switch
(command) case a finalValue
firstValue stdinScanner.nextInt()
break case s finalValue
firstValue stdinScanner.nextInt()
break case n finalValue -
firstValue break default
finalValue 0 System.out.println(Invalid
command command) System.out.println(Fin
al value is finalValue)
14
Rules for Using the Switch Statement
  • Always a break after every clause. Always.
  • Always a default clause. Always.
  • Must be used with primitive types (numbers and
    chars).
  • What is the problem if the input command is add
    or subtract or negate?
  • lets adapt the last example
  • How about a program that reads a numeric grade
    and computes the letter grade according to
  • 90 and above is A
  • 80 and above is B
  • below 80 is a C
Write a Comment
User Comments (0)
About PowerShow.com