ifi7184 lesson3

101
IFI7184.DT – Lesson 3

Upload: sonia

Post on 22-Jan-2018

376 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Ifi7184 lesson3

IFI7184.DT – Lesson 3

Page 2: Ifi7184 lesson3

Overview of today’s lesson

• On todays lesson we will address

– The Random and Math Classes

– The conditional statements

• If;

• if-else statement; and

• switch statement;

2015 @ Sonia Sousa 2

Page 3: Ifi7184 lesson3

Overview of Lesson 2

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

3

Page 4: Ifi7184 lesson3

Variables

• Primitive data

– Numerical• Integers: byte, short, int,

long

• Floating point decimals: float, double

– Characters:• Not complete strings:

char

– Boolean values:• Boolean: True or false

• Complex object

– Declare as instance of

a data class

• String

• Date

• Everything else

4

Page 5: Ifi7184 lesson3

Assignment Operators

• There are many assignment operators in

Java, including the following:

Operator

+=

-=

*=

/=

%=

Example

x += y

x -= y

x *= y

x /= y

x %= y

Equivalent To

x = x + y

x = x - y

x = x * y

x = x / y

x = x % y

5

Page 6: Ifi7184 lesson3

Math operators

• Arithmetic or math expressions that compute numeric results:

6

Addition

Subtraction

Multiplication

Division

Remainder

+

-

*

/

%

Page 7: Ifi7184 lesson3

Increment and Decrement

• The increment (++) operator

count++;

count = count + 1;

• The decrement (--) operator

count--;

count = count - 1;

7

Page 8: Ifi7184 lesson3

Comparative values

8

== Equal to

!= Not equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

Conditional Operators

&& Conditional-AND

|| Conditional-OR

?: Ternary (shorthand for

if-then-else statement)

Be careful When comparing strings

This will not work

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

Page 9: Ifi7184 lesson3

Overview of Lesson 2

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

9

Page 10: Ifi7184 lesson3

Class Libraries

• A class library is a collection of classes

– that we can use when developing programs

• Classes we've already used

– System , Scanner, String

– Those are part of the Java standard class library (java.lang)

• Java standard class library is part of

– Java development environment

10

Page 11: Ifi7184 lesson3

The Java class library

• Or the Java API

– Stands for Application Programming Interface

API

11

API documentation

http://docs.oracle.com/javase/6/docs/api/

Page 12: Ifi7184 lesson3

Packages

• Classes in the Java API are organized

– As packages

• These often overlap with specific APIs

• Examples:

12

Package

java.lang

java.applet

java.awt

javax.swing

java.net

java.util

javax.xml.parsers

Purpose

General support

Creating applets for the web

Graphics and graphical user interfaces

Additional graphics capabilities

Network communication

Utilities

XML document processing

Page 13: Ifi7184 lesson3

The import Declaration

• To use a class from a package,

– you need to import it

• You have 2 ways to do it

– Use the class name

import java.util.Scanner;

– import all classes in a particular package,

• use the * wildcard character

import java.util.*;

13

Page 14: Ifi7184 lesson3

The import Declaration

• java.lang package classes

– are imported automatically into all programs

import java.lang.*;

– That's why we didn't have to import the

• System or String classes in earlier programs

• Scanner class, on the other hand,

– is part of the java.util package, and therefore must be imported

14

Page 15: Ifi7184 lesson3

How to get input

• Scanner class

– The methods for reading input values of various types

import java.util class

• Scanner object uses System.in objects

– How to create a Scanner object

Scanner scan = new Scanner (System.in);

15

Scanner class is part of java.utilclass library

creates the Scanner object

Page 16: Ifi7184 lesson3

To read input from keyboard

• The nextLine method

– Reads all of the input until the end of the line is found

answer = scan.nextLine();

– See Echo.java exercise

16

Page 17: Ifi7184 lesson3

How to read input from keyboard

• Create a Scanner object

Scanner scan = new Scanner (System.in);

• Once created,

– Use it to invoke various input methods:

answer = scan.nextLine();

System.out.println (str.length());

System.out.println (str.substring(7));

System.out.println (str.toUpperCase());

System.out.println (str.length());

17

creates the Scanner object

Page 18: Ifi7184 lesson3

Invoking String Methods

• Use the dot operator to invoke its methods

numChars = title.length()

• A method may return a value,

– which can be used in an assignment or expression

18

Page 19: Ifi7184 lesson3

Outline

Class Libraries

The String Class

The Random and Math Classes

Formatting Output

Condition statements

The if Statement

Boolean Expressions

The switch Statement

19

Page 20: Ifi7184 lesson3

The Random Class

• The Random class

– is part of the java.util package

• It provides methods that generate pseudorandom numbers

• A Random object

– performs complicated calculations

• based on a seed value to produce a stream of seemingly random values

• See RandomNumbers.java

20

Page 21: Ifi7184 lesson3

//********************************************************************

// RandomNumbers.java Author: Lewis/Loftus

//

// Demonstrates the creation of pseudo-random numbers using the

// Random class.

//********************************************************************

import java.util.Random;

public class RandomNumbers

{

//-----------------------------------------------------------------

// Generates random numbers in various ranges.

//-----------------------------------------------------------------

public static void main (String[] args)

{

Random generator = new Random();

int num1;

float num2;

num1 = generator.nextInt();

System.out.println ("A random integer: " + num1);

num1 = generator.nextInt(10);

System.out.println ("From 0 to 9: " + num1);

continued

21

Page 22: Ifi7184 lesson3

continued

num1 = generator.nextInt(10) + 1;

System.out.println ("From 1 to 10: " + num1);

num1 = generator.nextInt(15) + 20;

System.out.println ("From 20 to 34: " + num1);

num1 = generator.nextInt(20) - 10;

System.out.println ("From -10 to 9: " + num1);

num2 = generator.nextFloat();

System.out.println ("A random float (between 0-1): " + num2);

num2 = generator.nextFloat() * 6; // 0.0 to 5.999999

num1 = (int)num2 + 1;

System.out.println ("From 1 to 6: " + num1);

}

}

22

Page 23: Ifi7184 lesson3

continued

num1 = generator.nextInt(10) + 1;

System.out.println ("From 1 to 10: " + num1);

num1 = generator.nextInt(15) + 20;

System.out.println ("From 20 to 34: " + num1);

num1 = generator.nextInt(20) - 10;

System.out.println ("From -10 to 9: " + num1);

num2 = generator.nextFloat();

System.out.println ("A random float (between 0-1): " + num2);

num2 = generator.nextFloat() * 6; // 0.0 to 5.999999

num1 = (int)num2 + 1;

System.out.println ("From 1 to 6: " + num1);

}

}

Sample Run

A random integer: 672981683

From 0 to 9: 0

From 1 to 10: 3

From 20 to 34: 30

From -10 to 9: -4

A random float (between 0-1): 0.18538326

From 1 to 6: 3

23

Page 24: Ifi7184 lesson3

Quick Check

• Given a Random object named gen, what range of values are produced by the following expressions?

24

gen.nextInt(25)

gen.nextInt(6) + 1

gen.nextInt(100) + 10

gen.nextInt(50) + 100

gen.nextInt(10) – 5

gen.nextInt(22) + 12

Range

0 to 24

1 to 6

10 to 109

100 to 149

-5 to 4

12 to 33

Page 25: Ifi7184 lesson3

Quick Check

• Given a Random object named gen, what range of values are produced by the following expressions?

25

gen.nextInt(25)

gen.nextInt(6) + 1

gen.nextInt(100) + 10

gen.nextInt(50) + 100

gen.nextInt(10) – 5

gen.nextInt(22) + 12

Sample Run

20

5

47

111

3

13

Page 26: Ifi7184 lesson3

Quick Check

• Write an expression that produces a random integer in the following ranges:

26

Range

0 to 12

1 to 20

15 to 20

-10 to 0

Page 27: Ifi7184 lesson3

Quick Check

Write an expression that produces a random integer

in the following ranges:

gen.nextInt(13)

gen.nextInt(20) + 1

gen.nextInt(6) + 15

gen.nextInt(11) – 10

Range

0 to 12

1 to 20

15 to 20

-10 to 0

27

Page 28: Ifi7184 lesson3

The Math Class

• The Math class is part of the java.langpackage

• The Math class contains methods that perform various mathematical functions

• These include:

– absolute value

– square root

– exponentiation

– trigonometric functions

28

Page 29: Ifi7184 lesson3

The Math Class

• The methods of the Math class are static methods (also called class methods)

• Static methods are invoked through the class name – no object of the Math class is needed

value = Math.cos(90) + Math.sqrt(delta);

• See squarertandpower.java

29

Page 30: Ifi7184 lesson3

Exercises

Small java programs to use of Math Class methods:

Math.sqrt and Math.pow

Page 31: Ifi7184 lesson3

31

//********************************************************************

// squarertandpower.java Author: Sónia Sousa

//

// Demonstrates the use of Math Class methods

//********************************************************************

Name of the class SquarertAndPower

// create a variable of type double name X (double x;)

// import java.util.Scanner;

// use method Scanner to scan a number from the keyboard

Scanner scan = new Scanner(System.in);

System.out.print(”Enter a number ");

x = scan.nextDouble();

// print out the square rote of X using Math.sqrt(x) Math Class method

The square route of "+ x +" is "+Math.sqrt(x)

// print out X raised to the power of 2 using Math.pow(x, 2) Math Class

method

x+” raised to the power of 2 is ”+Math.pow(x, 2)

Page 32: Ifi7184 lesson3

//********************************************************************

// squarertandpower.java Author: Isaias Barreto da rosa

//

// Demonstrates the use of Math Class methods

//********************************************************************

package squarertandpower;

import java.util.Scanner;

public class SquarertAndPower {

public static void main(String[] args) {

double x;

Scanner scan = new Scanner(System.in);

System.out.print(”Enter a number ");

x = scan.nextDouble();

System.out.println("The square route of "+ x +" is "+Math.sqrt(x));

System.out.println(x+” raised to the power of 2 is ”+Math.pow(x, 2));

}

}

32

Sample Run

Enter a number: 4

The square route of 4.0 is 2.0

4.0 raised to the power of 2 is 16.0

Page 33: Ifi7184 lesson3

Outline

Class Libraries

The String Class

The Random and Math Classes

Formatting Output

Condition statements

The if Statement

Boolean Expressions

The switch Statement

33

Page 34: Ifi7184 lesson3

Formatting Output

• Sometimes you need to format output values

– so that they can be presented properly.

• The Java standard class library (java.text)

– Includes classes that allows you to format

– The class name:

• NumberFormat: formats values as currency or percentages

• DecimalFormat: formats values (decimal numbers) based on a pattern

• Both are part of the java.text package

342015 @ Sonia Sousa

Page 35: Ifi7184 lesson3

Indentation

• Always use the use indentation style

– It makes a program easier to read and understand

• The statement controlled by the if statement

– is indented to indicate that relationship

35

"Always code as if the person who ends up

maintaining your code will be a violent

psychopath who knows where you live."

-- Martin Golding

2015 @ Sonia Sousa

Page 36: Ifi7184 lesson3

Indentation

• Remember

– Indentation helps to better read your program,

• Indentation is ignored by the compiler

if (depth >= UPPER_LIMIT)

delta = 100;

else

System.out.println("Reseting Delta");

delta = 0;

36

Despite what the indentation implies, delta will be set to 0

no matter what2015 @ Sonia Sousa

Page 37: Ifi7184 lesson3

Block Statements

• Several statements can be grouped together

– into a block statement delimited by braces

• A block statement can be used wherever

– a statement is called for in the Java syntax rules

37

if (total > MAX)

{

System.out.println ("Error!!");

errorCount++;

}

2015 @ Sonia Sousa

Page 38: Ifi7184 lesson3

Block Statements

• The if clause, or the else clause, or both,

– could govern block statements

38

if (total > MAX)

{

System.out.println ("Error!!");

errorCount++;

}

else

{

System.out.println ("Total: " + total);

current = total*2;

}2015 @ Sonia Sousa

Page 39: Ifi7184 lesson3

Nested if Statements

• A statement executed as a result of an if or else clause

– could be another if statement

• These are called nested if statements

– An else clause is matched to the last unmatched if (no matter what the indentation implies)

– Braces can be used to specify the if statement to which an else clause belongs

392015 @ Sonia Sousa

Page 40: Ifi7184 lesson3

Exercises

Small java programs to format Decimal values: DecimalFormat

Page 41: Ifi7184 lesson3

Outline

Class Libraries

The String Class

The Random and Math Classes

Formatting Output

Condition statements

The if Statement

Boolean Expressions

The switch Statement

41

Page 42: Ifi7184 lesson3

Condition statements

• A conditional statement

– Or selection statements

• lets us choose which statement will be executed next– give us the power to make basic decisions

• The Java conditional statements are the:

– If;

– if-else statement; and

– switch statement;

422015 @ Sonia Sousa

Page 43: Ifi7184 lesson3

The switch Statement

• The switch statement is another way

– to decide which statement to execute next

• The switch statement evaluates an expression, then

– See which results match a series of possible cases

• Each case contains a value and a list of statements

432015 @ Sonia Sousa

Page 44: Ifi7184 lesson3

Outline

Class Libraries

The String Class

The Random and Math Classes

Formatting Output

Condition statements

The if Statement

Boolean Expressions

The switch Statement

44

Page 45: Ifi7184 lesson3

If statement

• The if-then and if-then-else Statements

– Its is the most basic statement to evaluate a condition

• For example it tells your computer to execute a piece of code only if

– a particular test evaluates to true.

• If it is false then the– control jumps to the end of the if-then statement.

452015 @ Sonia Sousa

Page 46: Ifi7184 lesson3

The if Statement

• Let's now look at the if statement in more detail

– The if statement has the following syntax:

46

if ( condition )

statement;

if is a Java

reserved word

The condition must be a

boolean expression. It must

evaluate to either true or false.

If the condition is true, the statement is executed.

If not if it is false, the statement is skipped.

2015 @ Sonia Sousa

Page 47: Ifi7184 lesson3

Logic of an if statement

condition

evaluated

statement

true

false

472015 @ Sonia Sousa

Page 48: Ifi7184 lesson3

continue

System.out.println ("You entered: " + age);

if (age < MINOR)

System.out.println ("Youth is a wonderful thing. Enjoy.");

System.out.println ("Age is a state of mind.");

}

}

Sample Run

Enter your age: 47

You entered: 47

Age is a state of mind.

Another Sample Run

Enter your age: 12

You entered: 12

Youth is a wonderful thing. Enjoy.

Age is a state of mind.

482015 @ Sonia Sousa

Page 49: Ifi7184 lesson3

The if-else Statement

• An else clause can be added to an if statement to make an if-else statement

if ( condition )statement1;

elsestatement2;

• If the condition is true,

– statement1 is executed;

– if the condition is false, statement2 is executed

• One or the other will be executed, but not both

• See Wages.java

492015 @ Sonia Sousa

Page 50: Ifi7184 lesson3

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

502015 @ Sonia Sousa

Page 51: Ifi7184 lesson3

Nested if Statements

• A statement executed as a result of an if or elseclause

– could be another if statement

• These are called nested if statements

– An else clause is matched to the last unmatched if(no matter what the indentation implies)

– Braces can be used to specify the if statement to which an else clause belongs

• See MinOfThree.java

512015 @ Sonia Sousa

Page 52: Ifi7184 lesson3

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

52

Condition 2

evaluated

2015 @ Sonia Sousa

Page 53: Ifi7184 lesson3

continue

if (num1 < num2)

if (num1 < num3)

min = num1;

else

min = num3;

else

if (num2 < num3)

min = num2;

else

min = num3;

System.out.println ("Minimum value: " + min);

}

}

Sample Run

Enter three integers:

84 69 90

Minimum value: 69

532015 @ Sonia Sousa

Page 54: Ifi7184 lesson3

Outline

54

Class Libraries

The String Class

The Random and Math Classes

Formatting Output

Condition statements

The if Statement

Boolean Expressions

The switch Statement

2015 @ Sonia Sousa

Page 55: Ifi7184 lesson3

Boolean expressions

• The If condition is evaluated through a boolean expression.

• The boolean expression evaluates if

– the condition is true or false.

• Then execute the statement.

55

if ( condition )

statement;

2015 @ Sonia Sousa

Page 56: Ifi7184 lesson3

Boolean Expressions

• A boolean expression uses– Java's equality operators – or relational operators

• returns a boolean results (True or False)

• Equality operators are:== equal to!= not equal to

• Relational operators are:< less than> greater than<= less than or equal to>= greater than or equal to

56

Note: see difference between the equality operator (==) and the assignment operator (=)

2015 @ Sonia Sousa

Page 57: Ifi7184 lesson3

• An if statement with its boolean condition:

• First, the condition is evaluated:

– If the value of sum is: greater than the value of MAX,

– Then… the condition is true,

• Execute the statement;

– if not, skipped to execute the statement.

Boolean Expressions

57

if ( condition )

statement;

if (sum > MAX)

delta = sum – MAX;

2015 @ Sonia Sousa

Page 58: Ifi7184 lesson3

Quick Check

What do the following statement does?

if (total != (stock + warehouse))

inventoryError = true;

58

Sets the boolean variable to true if the value of total is not equal to the sum

of stock and warehouse

2015 @ Sonia Sousa

Page 59: Ifi7184 lesson3

Boolean Expressions

• Boolean expressions can also use the following – logical operators:

! Logical NOT

&& Logical AND

|| Logical OR

• They all take boolean operands and produce boolean results– Logical NOT is a unary operator (it operates on one

operand)

– Logical AND and logical OR are binary operators (each operates on two operands)

592015 @ Sonia Sousa

Page 60: Ifi7184 lesson3

Logical NOT

• The logical NOT operation – is also called logical negation or logical complement

• If some boolean condition a is true, then – !a is false; if

– a is false, then !a is true

• Logical expressions can be shown using a truth table:

60

a !a

true false

false true

2015 @ Sonia Sousa

Page 61: Ifi7184 lesson3

Logical AND and Logical OR

• The logical AND expression

a && b

– Condition: is true if both a and b are true,

• and false otherwise

• The logical OR expression

a || b

– Condition: is true if a or b or both are true,

• and false otherwise

612015 @ Sonia Sousa

Page 62: Ifi7184 lesson3

Logical AND and Logical OR

• The table shows all possible true-false combinations

– Since && and || each have two operands,

• there are four possible combinations of conditions aand b

62

a b a && b a || b

true true true true

true false false true

false true false true

false false false false

2015 @ Sonia Sousa

Page 63: Ifi7184 lesson3

Logical Operators

• Expressions that use logical operators

– can form complex conditions

if (total < MAX+5 && !found)

System.out.println ("Processing…");

• Note: logical operators have lower precedence

– Than the relational operators

– The ! operator has higher precedence than &&and ||

63

if ( condition )

statement;

2015 @ Sonia Sousa

Page 64: Ifi7184 lesson3

Boolean Expressions

• Specific expressions can be evaluated using truth tables

64

total < MAX found !found total < MAX && !found

false false true false

false true false false

true false true true

true true false false

2015 @ Sonia Sousa

Page 65: Ifi7184 lesson3

Quick Check

What do the following statements do?

65

if (found || !done)

System.out.println("Ok");

Prints "Ok" if found is true or done is false

2015 @ Sonia Sousa

Page 66: Ifi7184 lesson3

Short-Circuited Operators

• The processing of && and || is “short-circuited”

– this means…

• If the left operand is sufficient to determine the result, the right operand is not evaluated

if (count != 0 && total/count > MAX)System.out.println ("Testing.");

• This type of processing should be used carefully

662015 @ Sonia Sousa

Page 67: Ifi7184 lesson3

Exercises

If-then-else statement:

Page 68: Ifi7184 lesson3

68

//********************************************************************

// ConditionIf.java Author: Sónia Sousa

//

// Demonstrates the use of if-then-else statement

//********************************************************************

public class ConditionIf {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("Enter a number of the month (between 1 and 12)");

int i = scan.nextInt();

// structure of a if-then-else statement and the condition code

if ( i>=1 && i<=3) {

System.out.println("You have enter " + i + ", this month belongs to

the first quarter of the year");

}

else if (i>=4 && i <=6) {

System.out.println("You have enter " + i + ", this month belongs

to the second quarter of the year");

}

else {

System.out.println("You have enter " + i + ", this month does

not belongs to the first half of the year");

}

}

}

Page 69: Ifi7184 lesson3

Arithmetic or math expressions

69

Addition

Subtraction

Multiplication

Division

Remainder

+

-

*

/

%

Increment and Decrement

Increment operator

count++; or count = count + 1;

Decrement operator

count--; or count = count – 1;

Equal to

Not equal to

Greater than

Greater tan or equal to

Less than

Less than or equal to

==

!=

>

>=

<

<=

Conditional operators Boolean operators

Conditional-AND

Conditional-OR

Ternary

(shorthand for

if-then-else

statement

&&

||

?:

Page 70: Ifi7184 lesson3

Exercises

The use of an if-else statement

Page 71: Ifi7184 lesson3

Using an if statement

• Write a Java program (name it Age)

– That asks the user for their age (int) and then…

• Reads the user's age and prints comments accordingly.

– If statement if (age < MINOR)

System.out.println ("Youth is a wonderful thing.

Enjoy.");

– If not

• print comment “Age is a state of mind”

– Please follow the example provided in the next slide.

712015 @ Sonia Sousa

Page 72: Ifi7184 lesson3

Java program (name it Age)

– import java.util.Scanner;

– Variables:

• int minor, age; and minor = 18;

– Execute commands:

• Scanner scan = new Scanner (System.in)

• Print out (“Enter your age: “)

• Get the age = scan.nextInt();

• Print out the results

722015 @ Sonia Sousa

Page 73: Ifi7184 lesson3

continue

System.out.println ("You entered: " + age);

if (age < MINOR)

System.out.println ("Youth is a wonderful thing. Enjoy.");

System.out.println ("Age is a state of mind.");

}

}

Sample Run

Enter your age: 47

You entered: 47

Age is a state of mind.

Another Sample Run

Enter your age: 12

You entered: 12

Youth is a wonderful thing. Enjoy.

Age is a state of mind.

732015 @ Sonia Sousa

Page 74: Ifi7184 lesson3

Using an if-else statement

• Write a Java program (name it Wages)

– That asks the user for the number of hours of work and then… calculates wages and prints it.

• Regular pay rate is 8.25

• Overtime rate is = regular rate * 1.5

• Standard hours in a work week = 40

– If statement if (hours > standard)

pay = standard * rate+ (hours-standard) * (rate* 1.5);

else

pay = hours * rate;

– Please follow the example provided in the next slide.

742015 @ Sonia Sousa

Page 75: Ifi7184 lesson3

Java program (name it Wages)

– import java.util.Scanner class

– Variables: • int hours, standard;

• double rate, pay;

• pay = 0.0; rate= 8.25; standard = 40;

– Execute commands:• Scanner scan = new Scanner (System.in)

• Print out (“Enter the number of hours worked: “)

• Get the number of hours = scan.nextInt();

• Print out the Gross earnings.

752015 @ Sonia Sousa

Page 76: Ifi7184 lesson3

continue

System.out.print ("Enter the number of hours worked: ");

int hours = scan.nextInt();

// Pay overtime at "time and a half"

if (hours > standard)

pay = standard * rate+ (hours-standard) * (rate* 1.5);

else

pay = hours * rate;

System.out.println ("Gross earnings: " + pay + ” Euros”);

}

}

Sample Run

Enter the number of hours worked: 46

Gross earnings: 404.25 Euros

762015 @ Sonia Sousa

Page 77: Ifi7184 lesson3

Exercises

The use of Nested if Statements

Page 78: Ifi7184 lesson3

Nested if Statements

• A statement executed as a result of an if or else clause

– could be another if statement

• These are called nested if statements

– An else clause is matched to the last unmatched if (no matter what the indentation implies)

– Braces can be used to specify the if statement to which an else clause belongs

782015 @ Sonia Sousa

Page 79: Ifi7184 lesson3

Using Nested if statements• Write a Java program (name it Wages)

– That reads three integers from the user and determines the smallest value.

– Nested If statement if (num1 < num2)

if (num1 < num3)

min = num1;

else

min = num3;

else

if (num2 < num3)

min = num2;

else

min = num3;

– Please follow the example provided in the next slide.

792015 @ Sonia Sousa

Page 80: Ifi7184 lesson3

Java program (name it Wages)

– import java.util.Scanner class

– Variables:

int num1, num2, num3, min;

min = 0;

– Execute commands:

Scanner scan = new Scanner (System.in);

Print out (“Enter three integers: “ )

Get the number of num1, num2, num3= scan.nextInt();

Print out (“Minimum value: " + min);

802015 @ Sonia Sousa

Page 81: Ifi7184 lesson3

continue

if (num1 < num2)

if (num1 < num3)

min = num1;

else

min = num3;

else

if (num2 < num3)

min = num2;

else

min = num3;

System.out.println ("Minimum value: " + min);

}

}

Sample Run

Enter three integers:

84 69 90

Minimum value: 69

812015 @ Sonia Sousa

Page 82: Ifi7184 lesson3

Exercises

The use of Block if Statements

Page 83: Ifi7184 lesson3

Block Statements

• Several statements can be grouped together

– into a block statement delimited by braces

• A block statement can be used wherever

– a statement is called for in the Java syntax rules

83

if (total > MAX)

{

System.out.println ("Error!!");

errorCount++;

}

2015 @ Sonia Sousa

Page 84: Ifi7184 lesson3

Block Statements

• The if clause, or the else clause, or both,

– could govern block statements

84

if (total > MAX)

{

System.out.println ("Error!!");

errorCount++;

}

else

{

System.out.println ("Total: " + total);

current = total*2;

}2015 @ Sonia Sousa

Page 85: Ifi7184 lesson3

Using a Block if-else statement

• Write a Java program (name it Guessing) – That plays a simple guessing game with the user

• The program generates a random number and ask the user to guess and then… print and answer saying if h/she is correct or wrong.

– If-else statement if (guess == answer)

System.out.println ("You got it! Good guessing!");

else

{

System.out.println ("That is not correct, sorry.");

System.out.println ("The number was " + answer);

}

– Please follow the example provided in the next slide. 852015 @ Sonia Sousa

Page 86: Ifi7184 lesson3

Java program (name it Guessing)

– import java.util.* class

– Variables: • int MAX, answer, guess; and MAX= 10;

– Execute commands:• Scanner scan = new Scanner (System.in);

• Random generator = new Random();

• answer = generator.nextInt(MAX) + 1;

– Ask for the user to guess the number• Print out ("I'm thinking of a number between 1 and ” +

MAX + ". Guess what it is: ”)

• Get the number: guess = scan.nextInt();

862015 @ Sonia Sousa

Page 87: Ifi7184 lesson3

continue

System.out.print ("I'm thinking of a number between 1 and "

+ MAX + ". Guess what it is: ");

guess = scan.nextInt();

if (guess == answer)

System.out.println ("You got it! Good guessing!");

else

{

System.out.println ("That is not correct, sorry.");

System.out.println ("The number was " + answer);

}

}

}

Sample Run

I'm thinking of a number between 1 and 10. Guess what it is: 6

That is not correct, sorry.

The number was 9

872015 @ Sonia Sousa

Page 88: Ifi7184 lesson3

Outline

88

Class Libraries

The String Class

The Random and Math Classes

Formatting Output

Condition statements

The if Statement

Boolean Expressions

The switch Statement

2015 @ Sonia Sousa

Page 89: Ifi7184 lesson3

The switch Statement

• The switch statement is

– Another way to decide which statement to execute next

• The switch statement evaluates an expression,

– then attempts to match the result to one of several possible cases

• Each case contains a value and a list of statements

892015 @ Sonia Sousa

Page 90: Ifi7184 lesson3

The switch Statement

• The general syntax of a switch

statement is:

90

switch ( expression )

{

case value1 :

statement-list1

case value2 :

statement-list2

case value3 :

statement-list3

case ...

}

switch

andcase

are

reserved

words

If expression

matches value2,

control jumps

to here

2015 @ Sonia Sousa

Page 91: Ifi7184 lesson3

The switch Statement

• Often a break statement is used as the last statement in each case's statement list

• A break statement causes control to transfer to the end of the switch statement

• If a break statement is not used, the flow of control will continue into the next case

• Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

912015 @ Sonia Sousa

Page 92: Ifi7184 lesson3

The switch Statement

• An example of a switch statement:

92

switch (option)

{

case 'A':

aCount++;

break;

case 'B':

bCount++;

break;

case 'C':

cCount++;

break;

}

2015 @ Sonia Sousa

Page 93: Ifi7184 lesson3

The switch Statement

• A switch statement can have an optional default case

• The default case has no associated value and simply uses the reserved word default

• If the default case is present, control will transfer to it if no other case value matches

• If there is no default case, and no other value matches, control falls through to the statement after the switch

932015 @ Sonia Sousa

Page 94: Ifi7184 lesson3

The switch Statement

• The type of a switch expression must be integers, characters, or enumerated types

• As of Java 7, a switch can also be used with strings

• You cannot use a switch with floating point values

• The implicit boolean condition in a switchstatement is equality

• You cannot perform relational checks with a switch statement

• See GradeReport.java

942015 @ Sonia Sousa

Page 95: Ifi7184 lesson3

Exercises

Switch case statement:

Page 96: Ifi7184 lesson3

96

//********************************************************************

// switchStatement.java Author: Sónia Sousa

//

// Demonstrates the use of Switch statement

//********************************************************************

import java.util.*;

public class switchStatement {

public static void main(String[] args) {

// calling a class called getInput() that scans a number form the keyboard

String input=getInput();

// convert a String object to intinger with Integer.parseInt() method

int month = Integer.parseInt(input);

// statement evaluates an expression “the input month number”

switch (month) {

case 1:

System.out.println("The month is January");

break;

case 2:

System.out.println("The month is February");

break;

case 3:

System.out.println("The month is March");

break;

Page 97: Ifi7184 lesson3

97

case 4:

System.out.println("The month is April");

break;

case 5:

System.out.println("The month is May");

break;

case 6:

System.out.println("The month is june");

break;

default:

break;

}

}

private static String getInput(){

System.out.print("enter a number between 1 and 6: ");

Scanner scan = new Scanner (System.in);

return scan.nextLine();

}

}

Page 98: Ifi7184 lesson3

Exercise

The use of switch (case 1, case 2, …)

Page 99: Ifi7184 lesson3

//********************************************************************

// GradeReport.java Author: Lewis/Loftus

//

// Demonstrates the use of a switch statement.

//********************************************************************

import java.util.Scanner;

public class GradeReport

{

//-----------------------------------------------------------------

// Reads a grade from the user and prints comments accordingly.

//-----------------------------------------------------------------

public static void main (String[] args)

{

int grade, category;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter a numeric grade (0 to 100): ");

grade = scan.nextInt();

category = grade / 10;

System.out.print ("That grade is ");

continue

992015 @ Sonia Sousa

Page 100: Ifi7184 lesson3

continue

switch (category)

{

case 10:

System.out.println ("a perfect score. Well done.");

break;

case 9:

System.out.println ("well above average. Excellent.");

break;

case 8:

System.out.println ("above average. Nice job.");

break;

case 7:

System.out.println ("average.");

break;

case 6:

System.out.println ("below average. You should see the");

System.out.println ("instructor to clarify the material "

+ "presented in class.");

break;

default:

System.out.println ("not passing.");

}

}

}

1002015 @ Sonia Sousa

Page 101: Ifi7184 lesson3

continue

switch (category)

{

case 10:

System.out.println ("a perfect score. Well done.");

break;

case 9:

System.out.println ("well above average. Excellent.");

break;

case 8:

System.out.println ("above average. Nice job.");

break;

case 7:

System.out.println ("average.");

break;

case 6:

System.out.println ("below average. You should see the");

System.out.println ("instructor to clarify the material "

+ "presented in class.");

break;

default:

System.out.println ("not passing.");

}

}

}

Sample Run

Enter a numeric grade (0 to 100): 91

That grade is well above average. Excellent.

1012015 @ Sonia Sousa