SlideShare a Scribd company logo
1 of 101
IFI7184.DT – Lesson 3
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
Overview of Lesson 2
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
3
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
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
Math operators
• Arithmetic or math expressions that
compute numeric results:
6
Addition
Subtraction
Multiplication
Division
Remainder
+
-
*
/
%
Increment and Decrement
• The increment (++) operator
count++;
count = count + 1;
• The decrement (--) operator
count--;
count = count - 1;
7
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
Overview of Lesson 2
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
9
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
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/
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
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
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
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.util
class library
creates the Scanner object
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
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
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
Outline
Class Libraries
The String Class
The Random and Math Classes
Formatting Output
Condition statements
The if Statement
Boolean Expressions
The switch Statement
19
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
//********************************************************************
// 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
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
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
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
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
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
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
The Math Class
• The Math class is part of the java.lang
package
• The Math class contains methods that
perform various mathematical functions
• These include:
– absolute value
– square root
– exponentiation
– trigonometric functions
28
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
Exercises
Small java programs to use of Math
Class methods:
Math.sqrt and Math.pow
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)
//********************************************************************
// 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
Outline
Class Libraries
The String Class
The Random and Math Classes
Formatting Output
Condition statements
The if Statement
Boolean Expressions
The switch Statement
33
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
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
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 what
2015 @ Sonia Sousa
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
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
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
Exercises
Small java programs to format
Decimal values:
DecimalFormat
Outline
Class Libraries
The String Class
The Random and Math Classes
Formatting Output
Condition statements
The if Statement
Boolean Expressions
The switch Statement
41
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
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
Outline
Class Libraries
The String Class
The Random and Math Classes
Formatting Output
Condition statements
The if Statement
Boolean Expressions
The switch Statement
44
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
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
Logic of an if statement
condition
evaluated
statement
true
false
472015 @ Sonia Sousa
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
The if-else Statement
• An else clause can be added to an if statement to make an
if-else statement
if ( condition )
statement1;
else
statement2;
• 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
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
502015 @ Sonia Sousa
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
• See MinOfThree.java
512015 @ Sonia Sousa
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
52
Condition 2
evaluated
2015 @ Sonia Sousa
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
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
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
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
• 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
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
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
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
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
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 a
and 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
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
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
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
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
Exercises
If-then-else statement:
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");
}
}
}
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
&&
||
?:
Exercises
The use of an if-else statement
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
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
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
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
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
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
Exercises
The use of Nested if Statements
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
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
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
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
Exercises
The use of Block if Statements
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
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
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
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
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
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
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
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
and
case
are
reserved
words
If expression
matches value2,
control jumps
to here
2015 @ Sonia Sousa
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
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
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
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 switch
statement is equality
• You cannot perform relational checks with a
switch statement
• See GradeReport.java
942015 @ Sonia Sousa
Exercises
Switch case statement:
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;
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();
}
}
Exercise
The use of switch (case 1, case 2, …)
//********************************************************************
// 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
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
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

More Related Content

What's hot

Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for HaskellMartin Ockajak
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Javakjkleindorfer
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented ProgrammingAbdul Rahman Sherzad
 

What's hot (20)

Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Java introduction
Java introductionJava introduction
Java introduction
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
.NET F# Class constructor
.NET F# Class constructor.NET F# Class constructor
.NET F# Class constructor
 
Sep 15
Sep 15Sep 15
Sep 15
 
Sep 15
Sep 15Sep 15
Sep 15
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Java
JavaJava
Java
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Chap01
Chap01Chap01
Chap01
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented Programming
 

Viewers also liked

Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Sónia
 
Ifi7174 lesson1
Ifi7174 lesson1Ifi7174 lesson1
Ifi7174 lesson1Sónia
 
Literature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer ScienceLiterature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer ScienceClare Hooper
 
Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2Sónia
 
Ifi7184 lesson5
Ifi7184 lesson5Ifi7184 lesson5
Ifi7184 lesson5Sónia
 
Helping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviewsHelping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviewsThe Research Thing
 
Ifi7174 lesson4
Ifi7174 lesson4Ifi7174 lesson4
Ifi7174 lesson4Sónia
 
Technology, Trust, & Transparency
Technology, Trust, & TransparencyTechnology, Trust, & Transparency
Technology, Trust, & TransparencyGeek Girls
 
A key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsA key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsSónia
 
Trust workshop
Trust workshopTrust workshop
Trust workshopSónia
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Sónia
 
Technology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point FinalTechnology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point Finaljhustad1
 
A design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignA design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignSónia
 
Workshop 1
Workshop 1Workshop 1
Workshop 1Sónia
 
Technology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century GovernmentTechnology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century GovernmentTim O'Reilly
 
MG673 - Session 1
MG673 - Session 1MG673 - Session 1
MG673 - Session 1Sónia
 
Trust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and ModelsTrust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and ModelsClare Hooper
 

Viewers also liked (20)

Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective
 
Ifi7174 lesson1
Ifi7174 lesson1Ifi7174 lesson1
Ifi7174 lesson1
 
Literature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer ScienceLiterature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer Science
 
Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2
 
Ifi7184 lesson5
Ifi7184 lesson5Ifi7184 lesson5
Ifi7184 lesson5
 
Lesson 17
Lesson 17Lesson 17
Lesson 17
 
My ph.d Defence
My ph.d DefenceMy ph.d Defence
My ph.d Defence
 
Helping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviewsHelping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviews
 
Nettets genkomst?
Nettets genkomst?Nettets genkomst?
Nettets genkomst?
 
Ifi7174 lesson4
Ifi7174 lesson4Ifi7174 lesson4
Ifi7174 lesson4
 
Technology, Trust, & Transparency
Technology, Trust, & TransparencyTechnology, Trust, & Transparency
Technology, Trust, & Transparency
 
A key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsA key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactions
 
Trust workshop
Trust workshopTrust workshop
Trust workshop
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2
 
Technology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point FinalTechnology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point Final
 
A design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignA design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction Design
 
Workshop 1
Workshop 1Workshop 1
Workshop 1
 
Technology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century GovernmentTechnology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century Government
 
MG673 - Session 1
MG673 - Session 1MG673 - Session 1
MG673 - Session 1
 
Trust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and ModelsTrust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and Models
 

Similar to Ifi7184 lesson3

Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptMahyuddin8
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptghoitsun
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalorerajkamaltibacademy
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 

Similar to Ifi7184 lesson3 (20)

Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Core java
Core javaCore java
Core java
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
02basics
02basics02basics
02basics
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Methods
MethodsMethods
Methods
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
 
Core Java
Core JavaCore Java
Core Java
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 

More from Sónia

MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)Sónia
 
Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Sónia
 
IFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesIFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesSónia
 
IFI7184.DT about the course
IFI7184.DT about the courseIFI7184.DT about the course
IFI7184.DT about the courseSónia
 
Comparative evaluation
Comparative evaluationComparative evaluation
Comparative evaluationSónia
 
Ifi7155 Contextualization
Ifi7155 ContextualizationIfi7155 Contextualization
Ifi7155 ContextualizationSónia
 
Hcc lesson7
Hcc lesson7Hcc lesson7
Hcc lesson7Sónia
 
Hcc lesson6
Hcc lesson6Hcc lesson6
Hcc lesson6Sónia
 
eduHcc lesson2-3
eduHcc lesson2-3eduHcc lesson2-3
eduHcc lesson2-3Sónia
 
Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)Sónia
 
20 06-2014
20 06-201420 06-2014
20 06-2014Sónia
 
Ifi7155 project-final
Ifi7155 project-finalIfi7155 project-final
Ifi7155 project-finalSónia
 
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sónia
 
Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)Sónia
 
Workshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluationWorkshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluationSónia
 

More from Sónia (15)

MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)
 
Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Ifi7184.DT lesson 2
Ifi7184.DT lesson 2
 
IFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesIFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languages
 
IFI7184.DT about the course
IFI7184.DT about the courseIFI7184.DT about the course
IFI7184.DT about the course
 
Comparative evaluation
Comparative evaluationComparative evaluation
Comparative evaluation
 
Ifi7155 Contextualization
Ifi7155 ContextualizationIfi7155 Contextualization
Ifi7155 Contextualization
 
Hcc lesson7
Hcc lesson7Hcc lesson7
Hcc lesson7
 
Hcc lesson6
Hcc lesson6Hcc lesson6
Hcc lesson6
 
eduHcc lesson2-3
eduHcc lesson2-3eduHcc lesson2-3
eduHcc lesson2-3
 
Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)
 
20 06-2014
20 06-201420 06-2014
20 06-2014
 
Ifi7155 project-final
Ifi7155 project-finalIfi7155 project-final
Ifi7155 project-final
 
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
 
Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)
 
Workshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluationWorkshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluation
 

Recently uploaded

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Recently uploaded (20)

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

Ifi7184 lesson3

  • 2. 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
  • 3. Overview of Lesson 2 Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Creating Objects The String Class 3
  • 4. 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
  • 5. 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
  • 6. Math operators • Arithmetic or math expressions that compute numeric results: 6 Addition Subtraction Multiplication Division Remainder + - * / %
  • 7. Increment and Decrement • The increment (++) operator count++; count = count + 1; • The decrement (--) operator count--; count = count - 1; 7
  • 8. 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
  • 9. Overview of Lesson 2 Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Creating Objects The String Class 9
  • 10. 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
  • 11. 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/
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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.util class library creates the Scanner object
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. Outline Class Libraries The String Class The Random and Math Classes Formatting Output Condition statements The if Statement Boolean Expressions The switch Statement 19
  • 20. 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
  • 21. //******************************************************************** // 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. The Math Class • The Math class is part of the java.lang package • The Math class contains methods that perform various mathematical functions • These include: – absolute value – square root – exponentiation – trigonometric functions 28
  • 29. 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
  • 30. Exercises Small java programs to use of Math Class methods: Math.sqrt and Math.pow
  • 31. 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)
  • 32. //******************************************************************** // 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
  • 33. Outline Class Libraries The String Class The Random and Math Classes Formatting Output Condition statements The if Statement Boolean Expressions The switch Statement 33
  • 34. 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
  • 35. 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
  • 36. 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 what 2015 @ Sonia Sousa
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. Exercises Small java programs to format Decimal values: DecimalFormat
  • 41. Outline Class Libraries The String Class The Random and Math Classes Formatting Output Condition statements The if Statement Boolean Expressions The switch Statement 41
  • 42. 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
  • 43. 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
  • 44. Outline Class Libraries The String Class The Random and Math Classes Formatting Output Condition statements The if Statement Boolean Expressions The switch Statement 44
  • 45. 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
  • 46. 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
  • 47. Logic of an if statement condition evaluated statement true false 472015 @ Sonia Sousa
  • 48. 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
  • 49. The if-else Statement • An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; • 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
  • 50. Logic of an if-else statement condition evaluated statement1 true false statement2 502015 @ Sonia Sousa
  • 51. 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 • See MinOfThree.java 512015 @ Sonia Sousa
  • 52. Logic of an if-else statement condition evaluated statement1 true false statement2 52 Condition 2 evaluated 2015 @ Sonia Sousa
  • 53. 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
  • 54. 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
  • 55. 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
  • 56. 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
  • 57. • 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
  • 58. 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
  • 59. 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
  • 60. 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
  • 61. 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
  • 62. 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 a and 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
  • 63. 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
  • 64. 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
  • 65. 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
  • 66. 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
  • 68. 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"); } } }
  • 69. 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 && || ?:
  • 70. Exercises The use of an if-else statement
  • 71. 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
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. 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
  • 76. 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
  • 77. Exercises The use of Nested if Statements
  • 78. 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
  • 79. 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
  • 80. 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
  • 81. 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
  • 82. Exercises The use of Block if Statements
  • 83. 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
  • 84. 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
  • 85. 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
  • 86. 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
  • 87. 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
  • 88. 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
  • 89. 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
  • 90. 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 and case are reserved words If expression matches value2, control jumps to here 2015 @ Sonia Sousa
  • 91. 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
  • 92. 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
  • 93. 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
  • 94. 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 switch statement is equality • You cannot perform relational checks with a switch statement • See GradeReport.java 942015 @ Sonia Sousa
  • 96. 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;
  • 97. 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(); } }
  • 98. Exercise The use of switch (case 1, case 2, …)
  • 99. //******************************************************************** // 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
  • 100. 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
  • 101. 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