The document discusses Java user input using the Scanner class and various control flow statements in Java including if, if-else, and switch-case statements. It provides examples of how to take user input using the Scanner class and its nextLine() method. It then explains the logic and syntax of if, if-else and switch-case statements, including the use of boolean expressions and logical operators. It also discusses nested if statements and the purpose of the break statement in switch-case blocks.
This document provides instructions for Lab 2 of an Introduction to Java Technologies course. It includes prelab exercises on control flow and arrays, an activity demonstrating the different meanings of the + operator in Java, an activity modifying a sales data program, and an activity analyzing and coding a program to calculate average ratings from user-item rating data. Students are asked to complete the programming activities, submit a zip file of their source code, and a lab report answering the prelab questions and providing a conclusion. The report must be in Word or PDF format and include a cover page with specified information.
Dti2143 chap 4 control structures aka_selectionalish sha
Control structures determine the order of execution of statements in a program. There are three main types: sequential, selectional, and iterational. Selectional structures include if/else statements and switch cases, which allow different code blocks to execute based on conditions. Iterational structures like while, do-while, and for loops repeat a block of code a specified number of times. Nested control structures can embed one type within another. Proper use of conditions and logical operators is important for control flows to work as intended.
Dti2143 chap 4 control structures aka_selectionalish sha
Control structures determine the order of execution of statements in a program. There are three main types: sequential, selectional, and iterative. Selectional structures include if and switch statements. If statements allow for conditional execution of code based on boolean expressions. Switch statements select execution based on a variable's value and allow for multiple case blocks. Nested if statements involve if blocks within other if blocks.
The document discusses various Java control structures including boolean variables, if and if-else statements, and switch statements. It explains:
- Boolean variables store true/false values and are used to make conditional decisions in control structures.
- If statements allow executing code conditionally based on boolean expressions. If-else statements choose between two code blocks.
- Switch statements select code blocks based on an integer or character value using case labels.
- Nesting, boolean operators, and precedence rules allow complex conditional logic.
This document provides an introduction to Java programming concepts including what Java is, how to set up a Java development environment, basic Java code structure, variables, data types, arithmetic operations, conditional statements, loops, and getting user input. It covers elementary Java topics through examples and explanations. Key points include how to write, compile and run a simple Java program that prints "Hello World", how to declare and use variables of different data types, the different conditional statements (if, if-else, if-else-if-else), looping constructs (while, do-while, for), and taking user input using the Scanner class.
The document discusses control structures in C++ programming. It describes flow charts and their symbols used to represent algorithms. It then explains different types of control structures like selection structures (if, if/else) and repetition structures (while, for). Key points include:
- Flow charts use shapes like rectangles, diamonds, and arrows to visually depict a program's flow of execution.
- Selection structures like if and if/else allow a program to choose between alternative paths based on a conditional expression being true or false.
- Repetition structures like while and for allow certain operations to be repeated if a condition is met.
The document discusses different types of statements in Java including decision and repetition statements. It covers if, if-else, switch statements for decision making and while, do-while, for loops for repetition. It provides examples of each statement type and discusses when to use each one. It also covers block statements, comparing characters and strings, and avoiding infinite loops.
C Programming - Decision making, LoopingMURALIDHAR R
Execution of a statement or set of statement repeatedly is called as looping.
The loop may be executed a specified number of times and this depends on the satisfaction of a test condition.
A program loop is made up of two parts one part is known as body of the loop and the other is known as control condition.
Depending on the control condition statement the statements within the loop may be executed repeatedly.
Depending on the position of the control statement in the loop, a control structure may be classified either as an entry controlled loop or as an exit controlled loop.
Entry Controlled Loop:
When the control statement is placed before the body of the loop then such loops are called as entry controlled loops.
If the test condition in the control statement is true then only the body of the loop is executed.
If the test condition in the control statement is not true then the body of the loop will not be executed. If the test condition fails in the first checking itself the body of the loop will never be executed.
This chapter discusses:
1. Program flow control and statements like conditionals and loops that alter normal linear execution.
2. Conditional statements like if/else that allow choosing which statement executes based on a boolean condition.
3. Repetition statements like while and for loops that repeatedly execute a statement as long as/for as long as a condition is true.
Operator & control statements in C are used to perform operations and control program flow. Arithmetic operators (+, -, *, /, %) are used for mathematical calculations on integers and floating-point numbers. Relational operators (<, <=, >, >=, ==, !=) compare two operands. Logical operators (&&, ||, !) combine conditions. Control statements like if-else, switch, while, for, break, continue and goto alter program execution based on conditions.
This document discusses programming fundamentals and control structures in C++. It covers three main control structures: sequences which execute statements sequentially, repetition (looping) which repeats statements while a condition is met, and selection (branching) which executes instructions depending on conditions. Specific structures covered include if/else, switch, while, do-while, for, and nested loops. Control flow and how these structures direct a program's execution is also explained.
The document discusses various control flow statements in C++ including relational operators, loops (for, while, do-while), decisions (if, if-else, switch), logical operators, and other statements like break, continue, and goto. It provides examples and explanations of how each statement works, when they should be used, and precedence of operators.
The document discusses topics covered in Lecture 3 of a Java programming course, including conditional statements, Boolean operators, if and else statements, and variable scopes. Conditional statements allow different code blocks to execute depending on logical conditions. Local variables declared within methods have narrower scopes than instance and class variables. The lecture will also cover Boolean types and operators, implementing if/else conditional logic, and differentiating variable types and scopes.
Java Chapter 05 - Conditions & Loops: part 3DanWooster1
This document summarizes parts of Chapter 5 from a Java programming textbook. It discusses boolean expressions and conditional statements like if, if-else, and nested if statements in Java. Key concepts covered include the syntax of if and if-else statements, using block statements with conditionals, and ensuring proper indentation to avoid logic errors in nested conditional statements. Examples include finding the minimum of three numbers and a coin flipping simulation class.
The Three Basic Selection Structures in C++ Programming ConceptsTech
Now check the powerpoint presentation about selection structures in programming. For more visit www.techora.net
Three types of selection structures are available like :
1 - Sequence Structure
2 - Selection Strcuture
3 - Repetition Structure
In this PPT slide, we discuss about the selection structure
1 - if statements
2 - if else statement
3 - switch statement
The document discusses different types of control structures in Java, including sequential, selection, and repetition structures. It focuses on selection structures such as if, if-else, and switch statements. The if statement and if-else statement are explained with examples, including using logical operators and block statements. The switch statement is also covered, highlighting the use of break statements. Multiple selection structures like nested if statements are demonstrated.
Chapter 3 introduces several Java program statements:
- Conditional statements like if-else allow programs to make decisions based on boolean expressions.
- Loops like while and for allow code to repeat based on conditions.
- Logical operators like && and || combine boolean expressions.
- Proper program design is important, involving requirements, design, implementation, and testing stages.
Fundamental of Information Technology - UNIT 8Shipra Swati
This document discusses different types of control structures in C programming including sequence control, selection/decision control, case control, and repetition/loop control. It provides examples of if, if-else, switch, for, and while loops. The if statement and if-else statement are used for decision making and branching based on a condition being true or false. Switch statements provide an alternative for nested if-else statements. Loops like for and while are used to repeat a block of code until a condition is met. Examples are given to calculate the sum of natural numbers using for and while loops.
The document discusses 3 types of flow control in programming: sequential, selection, and repetition. Selection structures like the if statement allow a program to select one of multiple execution paths based on a boolean conditional expression. There are 3 types of selection structures in Java: if statements, if-else statements, and switch statements. The if statement executes its statement block if the condition evaluates to true, and skips it if false. Boolean expressions use equality and relational operators to return true or false. Multiple statements can be grouped into a block for an if statement.
The document discusses various control structures and functions used in Arduino programming including decision making structures like if, else if, else statements and switch case statements. It also covers different types of loops like while, do-while and for loops that allow repeating blocks of code. Functions are described as reusable blocks of code that perform tasks and help organize a program. Strings can be implemented as character arrays or using the String class, and various string functions are provided to manipulate and work with strings.
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
The document discusses various Java data types including primitive data types like byte, short, int, long, float, double, char, boolean and their ranges. It also explains variables in Java - local variables, instance variables, static variables. Different types of operators like arithmetic, assignment, comparison, logical, bitwise operators are defined along with examples. The document also covers conditional statements like if-else, switch case and different loops in Java - for, while, do-while loops along with examples. Break and continue statements in Java loops are also explained.
The document discusses different types of statements in Java including decision and repetition statements. It covers if, if-else, switch statements for decision making and while, do-while, for loops for repetition. It provides examples of each statement type and discusses when to use each one. It also covers block statements, comparing characters and strings, and avoiding infinite loops.
C Programming - Decision making, LoopingMURALIDHAR R
Execution of a statement or set of statement repeatedly is called as looping.
The loop may be executed a specified number of times and this depends on the satisfaction of a test condition.
A program loop is made up of two parts one part is known as body of the loop and the other is known as control condition.
Depending on the control condition statement the statements within the loop may be executed repeatedly.
Depending on the position of the control statement in the loop, a control structure may be classified either as an entry controlled loop or as an exit controlled loop.
Entry Controlled Loop:
When the control statement is placed before the body of the loop then such loops are called as entry controlled loops.
If the test condition in the control statement is true then only the body of the loop is executed.
If the test condition in the control statement is not true then the body of the loop will not be executed. If the test condition fails in the first checking itself the body of the loop will never be executed.
This chapter discusses:
1. Program flow control and statements like conditionals and loops that alter normal linear execution.
2. Conditional statements like if/else that allow choosing which statement executes based on a boolean condition.
3. Repetition statements like while and for loops that repeatedly execute a statement as long as/for as long as a condition is true.
Operator & control statements in C are used to perform operations and control program flow. Arithmetic operators (+, -, *, /, %) are used for mathematical calculations on integers and floating-point numbers. Relational operators (<, <=, >, >=, ==, !=) compare two operands. Logical operators (&&, ||, !) combine conditions. Control statements like if-else, switch, while, for, break, continue and goto alter program execution based on conditions.
This document discusses programming fundamentals and control structures in C++. It covers three main control structures: sequences which execute statements sequentially, repetition (looping) which repeats statements while a condition is met, and selection (branching) which executes instructions depending on conditions. Specific structures covered include if/else, switch, while, do-while, for, and nested loops. Control flow and how these structures direct a program's execution is also explained.
The document discusses various control flow statements in C++ including relational operators, loops (for, while, do-while), decisions (if, if-else, switch), logical operators, and other statements like break, continue, and goto. It provides examples and explanations of how each statement works, when they should be used, and precedence of operators.
The document discusses topics covered in Lecture 3 of a Java programming course, including conditional statements, Boolean operators, if and else statements, and variable scopes. Conditional statements allow different code blocks to execute depending on logical conditions. Local variables declared within methods have narrower scopes than instance and class variables. The lecture will also cover Boolean types and operators, implementing if/else conditional logic, and differentiating variable types and scopes.
Java Chapter 05 - Conditions & Loops: part 3DanWooster1
This document summarizes parts of Chapter 5 from a Java programming textbook. It discusses boolean expressions and conditional statements like if, if-else, and nested if statements in Java. Key concepts covered include the syntax of if and if-else statements, using block statements with conditionals, and ensuring proper indentation to avoid logic errors in nested conditional statements. Examples include finding the minimum of three numbers and a coin flipping simulation class.
The Three Basic Selection Structures in C++ Programming ConceptsTech
Now check the powerpoint presentation about selection structures in programming. For more visit www.techora.net
Three types of selection structures are available like :
1 - Sequence Structure
2 - Selection Strcuture
3 - Repetition Structure
In this PPT slide, we discuss about the selection structure
1 - if statements
2 - if else statement
3 - switch statement
The document discusses different types of control structures in Java, including sequential, selection, and repetition structures. It focuses on selection structures such as if, if-else, and switch statements. The if statement and if-else statement are explained with examples, including using logical operators and block statements. The switch statement is also covered, highlighting the use of break statements. Multiple selection structures like nested if statements are demonstrated.
Chapter 3 introduces several Java program statements:
- Conditional statements like if-else allow programs to make decisions based on boolean expressions.
- Loops like while and for allow code to repeat based on conditions.
- Logical operators like && and || combine boolean expressions.
- Proper program design is important, involving requirements, design, implementation, and testing stages.
Fundamental of Information Technology - UNIT 8Shipra Swati
This document discusses different types of control structures in C programming including sequence control, selection/decision control, case control, and repetition/loop control. It provides examples of if, if-else, switch, for, and while loops. The if statement and if-else statement are used for decision making and branching based on a condition being true or false. Switch statements provide an alternative for nested if-else statements. Loops like for and while are used to repeat a block of code until a condition is met. Examples are given to calculate the sum of natural numbers using for and while loops.
The document discusses 3 types of flow control in programming: sequential, selection, and repetition. Selection structures like the if statement allow a program to select one of multiple execution paths based on a boolean conditional expression. There are 3 types of selection structures in Java: if statements, if-else statements, and switch statements. The if statement executes its statement block if the condition evaluates to true, and skips it if false. Boolean expressions use equality and relational operators to return true or false. Multiple statements can be grouped into a block for an if statement.
The document discusses various control structures and functions used in Arduino programming including decision making structures like if, else if, else statements and switch case statements. It also covers different types of loops like while, do-while and for loops that allow repeating blocks of code. Functions are described as reusable blocks of code that perform tasks and help organize a program. Strings can be implemented as character arrays or using the String class, and various string functions are provided to manipulate and work with strings.
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
The document discusses various Java data types including primitive data types like byte, short, int, long, float, double, char, boolean and their ranges. It also explains variables in Java - local variables, instance variables, static variables. Different types of operators like arithmetic, assignment, comparison, logical, bitwise operators are defined along with examples. The document also covers conditional statements like if-else, switch case and different loops in Java - for, while, do-while loops along with examples. Break and continue statements in Java loops are also explained.
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Leonel Morgado
Slides used at the Invited Talk at the Harvard - Education University of Hong Kong - Stanford Joint Symposium, "Emerging Technologies and Future Talents", 2025-05-10, Hong Kong, China.
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18Celine George
In this slide, we’ll discuss on how to clean your contacts using the Deduplication Menu in Odoo 18. Maintaining a clean and organized contact database is essential for effective business operations.
Happy May and Taurus Season.
♥☽✷♥We have a large viewing audience for Presentations. So far my Free Workshop Presentations are doing excellent on views. I just started weeks ago within May. I am also sponsoring Alison within my blog and courses upcoming. See our Temple office for ongoing weekly updates.
https://ldmchapels.weebly.com
♥☽About: I am Adult EDU Vocational, Ordained, Certified and Experienced. Course genres are personal development for holistic health, healing, and self care/self serve.
How to Create Kanban View in Odoo 18 - Odoo SlidesCeline George
The Kanban view in Odoo is a visual interface that organizes records into cards across columns, representing different stages of a process. It is used to manage tasks, workflows, or any categorized data, allowing users to easily track progress by moving cards between stages.
Happy May and Happy Weekend, My Guest Students.
Weekends seem more popular for Workshop Class Days lol.
These Presentations are timeless. Tune in anytime, any weekend.
<<I am Adult EDU Vocational, Ordained, Certified and Experienced. Course genres are personal development for holistic health, healing, and self care. I am also skilled in Health Sciences. However; I am not coaching at this time.>>
A 5th FREE WORKSHOP/ Daily Living.
Our Sponsor / Learning On Alison:
Sponsor: Learning On Alison:
— We believe that empowering yourself shouldn’t just be rewarding, but also really simple (and free). That’s why your journey from clicking on a course you want to take to completing it and getting a certificate takes only 6 steps.
Hopefully Before Summer, We can add our courses to the teacher/creator section. It's all within project management and preps right now. So wish us luck.
Check our Website for more info: https://ldmchapels.weebly.com
Get started for Free.
Currency is Euro. Courses can be free unlimited. Only pay for your diploma. See Website for xtra assistance.
Make sure to convert your cash. Online Wallets do vary. I keep my transactions safe as possible. I do prefer PayPal Biz. (See Site for more info.)
Understanding Vibrations
If not experienced, it may seem weird understanding vibes? We start small and by accident. Usually, we learn about vibrations within social. Examples are: That bad vibe you felt. Also, that good feeling you had. These are common situations we often have naturally. We chit chat about it then let it go. However; those are called vibes using your instincts. Then, your senses are called your intuition. We all can develop the gift of intuition and using energy awareness.
Energy Healing
First, Energy healing is universal. This is also true for Reiki as an art and rehab resource. Within the Health Sciences, Rehab has changed dramatically. The term is now very flexible.
Reiki alone, expanded tremendously during the past 3 years. Distant healing is almost more popular than one-on-one sessions? It’s not a replacement by all means. However, its now easier access online vs local sessions. This does break limit barriers providing instant comfort.
Practice Poses
You can stand within mountain pose Tadasana to get started.
Also, you can start within a lotus Sitting Position to begin a session.
There’s no wrong or right way. Maybe if you are rushing, that’s incorrect lol. The key is being comfortable, calm, at peace. This begins any session.
Also using props like candles, incenses, even going outdoors for fresh air.
(See Presentation for all sections, THX)
Clearing Karma, Letting go.
Now, that you understand more about energies, vibrations, the practice fusions, let’s go deeper. I wanted to make sure you all were comfortable. These sessions are for all levels from beginner to review.
Again See the presentation slides, Thx.
All About the 990 Unlocking Its Mysteries and Its Power.pdfTechSoup
In this webinar, nonprofit CPA Gregg S. Bossen shares some of the mysteries of the 990, IRS requirements — which form to file (990N, 990EZ, 990PF, or 990), and what it says about your organization, and how to leverage it to make your organization shine.
Learn about the APGAR SCORE , a simple yet effective method to evaluate a newborn's physical condition immediately after birth ....this presentation covers .....
what is apgar score ?
Components of apgar score.
Scoring system
Indications of apgar score........
Lecture 1 Introduction history and institutes of entomology_1.pptxArshad Shaikh
*Entomology* is the scientific study of insects, including their behavior, ecology, evolution, classification, and management.
Entomology continues to evolve, incorporating new technologies and approaches to understand and manage insect populations.
What makes space feel generous, and how architecture address this generosity in terms of atmosphere, metrics, and the implications of its scale? This edition of #Untagged explores these and other questions in its presentation of the 2024 edition of the Master in Collective Housing. The Master of Architecture in Collective Housing, MCH, is a postgraduate full-time international professional program of advanced architecture design in collective housing presented by Universidad Politécnica of Madrid (UPM) and Swiss Federal Institute of Technology (ETH).
Yearbook MCH 2024. Master in Advanced Studies in Collective Housing UPM - ETH
Title: A Quick and Illustrated Guide to APA Style Referencing (7th Edition)
This visual and beginner-friendly guide simplifies the APA referencing style (7th edition) for academic writing. Designed especially for commerce students and research beginners, it includes:
✅ Real examples from original research papers
✅ Color-coded diagrams for clarity
✅ Key rules for in-text citation and reference list formatting
✅ Free citation tools like Mendeley & Zotero explained
Whether you're writing a college assignment, dissertation, or academic article, this guide will help you cite your sources correctly, confidently, and consistent.
Created by: Prof. Ishika Ghosh,
Faculty.
📩 For queries or feedback: [email protected]
Computer crime and Legal issues Computer crime and Legal issuesAbhijit Bodhe
• Computer crime and Legal issues: Intellectual property.
• privacy issues.
• Criminal Justice system for forensic.
• audit/investigative.
• situations and digital crime procedure/standards for extraction,
preservation, and deposition of legal evidence in a court of law.
2. Outline
The if Statement and
Conditions Other Conditional
Statements Comparing Data
After midterm:
The while
Statement Iterators
Other Repetition
Statements
3. Flow of
Control
Unless specified otherwise, the order of statement execution
through a method is linear: one statement after another in
sequence
Some programming statements allow us to:
decide whether or not to execute a particular statement
execute a statement over and over, repetitively
These decisions are based on booleanexpressions(or conditions)
that evaluate to true or false
The order of statement execution is called the flow of control
4. Conditional
Statements
Aconditional statement lets us choose which statement will be
executed next
Therefore they are sometimescalled selection statements
Conditional statements give us the power to make basic
decisions
The Java conditional statements are the:
if statement
if-else statement
switch statement
5. The if
Statement
if is a Java
reserved word
The if statement has the following syntax:
The condition must be a
boolean expression. It must
evaluate to either true or
false.
if ( condition )
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
6. Logic of an if
statement
state ment
condition
evaluated
tru
e
f
a
l
s
e
7. Boolean
Expressions
Acondition often uses one of Java's equality operatorsor
relational operators, which all return boolean results:
==
!=
<
>
<=
>=
equal to
not equal
to less
than
greater
than
less than or equal to
greater than or equal
to
Note the difference between the equality operator (==) and
the assignment operator (=)
8. The if
Statement
An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);
•
• First the condition is evaluated -- the value of sum
is either greater than the value of MAX, or it is not
If the condition is true, the assignment statement
is executed -- if it isn’t, it is skipped.
• Either way, the call to println is executed
next
9. Age.jav
a
…
public static void main (String[] args)
{
final int MINOR = 21;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter your age: ");
int age = scan.nextInt();
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.");
}
}
10. Age.java
Output
----jGRASP exec: java Age
Enter your age: 12
You entered: 12
Youth is a wonderful thing. Enjoy.
Age is a state of mind.
----jGRASP: operation complete.
----jGRASP exec: java Age
Enter your age: 100
You entered: 100
Age is a state of mind.
----jGRASP: operation
11. Indentation
The statement controlled by the if statement is indented to
indicate that relationship
The use of a consistent indentation style makes a program
easier to read and understand
Although it makes no difference to the compiler, proper
indentation is crucial
"Always code as if the person who ends up
maintaining your code will be a violent
psychopath who knows where you live."
-- Martin Golding
12. The if
Statement
What do the following statements do?
if (top >= MAXIMUM)
top = 0;
Sets top to zero if the current value of top is greater
than or equal to the value of MAXIMUM
if (total != stock + warehouse)
inventoryError = true;
Sets a flag to true if the value of total is not equal to
the sum of stock and warehouse
• The precedence of the arithmetic operators is
higher than the precedence of the equality and
relational operators
13. Logical
Operators
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)
14. Logical
NOT
The logical NOToperation 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
a
true
false
!a
false
true
15. Logical AND and Logical
OR
The logical AND expression
a && b
is true if both a and b are true, and false
otherwise
The logical OR expression
a || b
is true if a or b or both are true, and false
otherwise
16. Logical
Operators
Expressions that use logical operators can form complex
conditions
if (total < MAX+5 && !found)
System.out.println ("Processing…");
• All logical operators have lower precedence than
the relational operators
• Logical NOT has higher precedence than logical
AND and logical OR
17. Logical
Operators
Atruth table shows all possible true-false combinations of the
terms
Since && and || each have two operands, there are
four possible combinations of conditions a and b
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
18. Boolean
Expressions
Specific expressions can be evaluated using truth tables
total < MAX found !found total < MAX && !found
false
false
true
true
false
true
false
true
true
false
true
false
false
false
true
false
19. English conditions in
Java
true if ch is the first letter in the alphabet
Test if a variable’s value is within a specified range
true if x is between min and max inclusive (including
min and max)
true if x is between min and max exclusive (excluding the
endpoints
Test if variable’s value is outside the range
true if x is less than min or greater than max
20. Testin
g
Execute all paths through the program
Recall the flow-chart
Good idea to test all combinations of an && and a ||
When numeric ranges, test the values around change in
behavior
Not necessary to test all possible values
Most cases it is impossible to test exhaustively
22. The if-else
Statement
An elseclausecan be added to an if statement to make an
if- else statement
if ( condition )
statement1;
else
statemen
t2;
•
• 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
23. from Wages.java
final double RATE = 8.25; // regular pay rate
final int STANDARD = 40; // standard hours in a work
// week
Scanner scan = new Scanner (System.in);
double pay = 0.0;
System.out.print ("Enter the number of hours worked: ");
int hours = scan.nextInt();
System.out.println ();
// Pay overtime at "time and a half"
if (hours > STANDARD)
pay = STANDARD * RATE + (hours-STANDARD) *
(RATE * 1.5);
else
pay = hours * RATE;
24. Logic of an if-else
statement
condition
evaluated
statement1
true false
statement 2
25. if Statement with Two
Alternatives
Statements that print “February has 29 days” if it is a leap year and otherwise
prints “February has 28 days”
Hint: Requires the else statement
int leapYear = scan.nextInt()
26. The Coin
Class
Let's examine a class that represents a coin that can be flipped
Instance data is used to indicate which face (heads or tails) is
currently showing
//
************************************************************
*
// Coin.java Author: Lewis/Loftus
//
// Represents a coin with two sides that can be flipped.
//
************************************************************
*
public class Coin
{
private static final int HEADS = 0;
private static final int TAILS = 1;
private int face;
27. Coin.java
//----------------------------------------------------------
// Sets up the coin by flipping it initially.
//----------------------------------------------------------
public Coin ()
{
flip();
}
//----------------------------------------------------------
// Flips the coin by randomly choosing a face value.
//----------------------------------------------------------
public void flip ()
{
face = (int) (Math.random() * 2);
}
//----------------------------------------------------------
// Returns true if the current face of the coin is heads.
//----------------------------------------------------------
public boolean isHeads ()
{
return (face == HEADS);
}
29. CoinFlip.java
//*************************************************************
// CoinFlip.java Author: Lewis/Loftus
//
// Demonstrates the use of an if-else statement.
//*************************************************************
public class CoinFlip
{
//----------------------------------------------------------
// Creates a Coin object, flips it, and prints the
results.
//----------------------------------------------------------
public static void main (String[] args)
{
Coin myCoin = new Coin();
myCoin.flip();
System.out.println (myCoin);
if (myCoin.isHeads())
System.out.println ("You win.");
else
System.out.println ("Better
luck next time.");
}
}
30. else if
drift
String grdStr;
if (grade >= 90)
grdStr = “A”;
else
if (grade
>= 80)
grdStr = “B”;
else
if (grade >= 70)
grdStr = “C”;
else
if (grade >= 60)
grdStr = “D”;
else
grdStr = “F”;
String grdStr;
if (grade >= 90)
grdStr = “A”;
else if (grade >= 80)
grdStr = “B”;
else if (grade >= 70)
grdStr = “C”;
else if (grade >= 60)
grdStr = “D”;
else
grdStr =
“F”;
31. Indentation
Revisited
Remember that indentation is for the human reader, and is
ignored by the computer
if (total > MAX)
System.out.println ("Error!!");
errorCount++;
Despite what is implied by the indentation, the
increment will occur whether the condition is
true or not
32. Block
Statements
Several statements can be grouped together into a block
statement delimited by braces
Ablock statement can be used wherever a statement is called
for in the Java syntax rules
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
33. Block
Statements
In an if-else statement, the if portion, or the
else
portion, or both, could be block statements
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}
34. Guessing.java
…
final int MAX = 10;
int answer, guess;
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
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);
}
}
}
35. Nested if
Statements
The statement executed as a result of an if statement 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
36. MinOfThree.java
…
int num1, num2, num3, min = 0;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter three integers: ");
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 =
scan.nextInt();
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);
}
}
37. Importance of Curly
Braces
Print “Wehave a problem” if examGrade < 60
Print “Wehave a real problem” if examGrade < 60 and
quizGrade < 10
Print “Ok” if examGrade >= 60
int examGrade, quizGrade;
if (examGrade < 60)
System.out.println(“We have a problem”);
if (quizGrade < 10)
System.out.println(“We have a real problem”);
else
System.out.println(“Ok”);
38. Exam Grade
Flowchart
int examGrade, quizGrade;
if (examGrade < 60)
System.out.println(“We have a problem”);
if (quizGrade < 10)
System.out.println(“We have a real problem”);
else
System.out.println(“Ok”);
39. Writing
Cases
Print “Wehave a problem” if examGrade < 60
Print “Wehave a real problem” if examGrade < 60 and quizGrade <
10
Print “Ok” if examGrade >= 60
examGrade < 60 quizGrade < 10 Action
Case 1 “We have a problem”
Case 2 “We have a problem” and
“We have a real
problem”
Case 3 “Ok”
41. The switch
Statement
The switch statement provides 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
The flow of control transfers to statement associated with
the first case value that matches
42. The switch Statement
The general syntax of a switch statement is:
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
43. 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
44. The switch
Statement
An example of a switch statement:
switch (option)
{
case 'A':
aCount++; break;
case 'B':
bCount++; break;
case 'C':
cCount++; break;
}
45. The switch
Statement
Aswitch statement can have an optional default case
The default case has no associated value and simplyuses the
reserved word default
If the default caseis 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
46. The switch
Statement
The expression of a switch statement must result in an
integral type,meaning an int or a char
It cannot be a boolean value, a floating point
value (float or double), or another integer
type
The implicit boolean condition in a switch statement is
equality
You cannot perform relational checks with a switch
statement
47. GradeReport.java
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 ");
48. GradeReport.java
switch (category)
{
case 10:
System.out.println ("a perfect score. Well done.");
break;
case 9:
System.out.println ("well above average. Great.");
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.");
System.out.println ("See the instructor.");
break;
default:
System.out.println ("not passing.");
}
}
}
50. Comparing
Data
When comparing data using boolean expressions, it's
important to understand the nuances of certain data
types
Let's examine some key situations:
Comparing floating point values for equality
Comparing characters
Comparing strings (alphabetical order)
Comparing object vs. comparing object references
51. Comparing Float
Values
You should rarely use the equality operator (==) when
comparing two floating point values (float or
double)
Two floating point values are equal only if their underlying
binary representations match exactly
Computations often result in slight differences that may be
irrelevant
In many situations, you might consider two floating point
numbers to be "close enough" even if they aren't exactly
equal
52. Comparing Float
Values
To determine the equality of two floats, you may want to use
the following technique:
if (Math.abs(f1 - f2) < TOLERANCE)
System.out.println ("Essentially equal");
• If the difference between the two floating point
values is less than the tolerance, they are
considered to be equal
• The tolerance could be set to any appropriate
level, such as 0.000001
53. Comparing
Characters
As we've discussed, Java character data is based on the
Unicode character set
Unicode establishes a particular numeric value for each
character, and therefore an ordering
We can use relational operators on character data based on
this ordering
For example, the character '+' is less than the character
'J'
because it comes before it in the Unicode character set
Appendix C provides an overview of Unicode
54. Comparing
Characters
In Unicode, the digit characters (0-9) are contiguous and in
order
Likewise, the uppercase letters (A-Z) and lowercase letters
(a-
z) are contiguous and in order
Characters
0 – 9
A – Z
a – z
Unicode Values
48 through 57
65 through 90
97 through 122
55. Comparing
Strings
Remember that in Javaa character string is an object
The equals method can be called with strings to
determine if two strings contain exactly the same characters
in the same order
The equals method returns a boolean result
if (name1.equals(name2))
System.out.println ("Same name");
56. Comparing
Strings
We cannot use the relational operators to compare strings
The String class contains a method called compareTo
to determine if one string comes before another
Acall to name1.compareTo(name2)
returns zero if name1 and name2 are equal (contain
the same characters)
returns a negative value if name1 is less than name2
returns a positive value if name1 is greater than name2
57. Comparing
Strings
if (name1.compareTo(name2) < 0)
System.out.println (name1 + "comes first");
else
if (name1.compareTo(name2) == 0)
System.out.println ("Same name");
else
System.out.println (name2 + "comes
first");
• Because comparing characters and strings is
based on a character set, it is called a
lexicographic ordering
58. Lexicographic
Ordering
Lexicographic ordering is not strictly alphabeticalwhen
uppercase and lowercase characters are mixed
For example, the string "Great" comes before the string
"fantastic" because all of the uppercase letters
come before all of the lowercase letters in Unicode
Also, short strings come before longer strings with the same
prefix (lexicographically)
Therefore "book" comes before "bookcase"
59. Comparing
Objects
The == operator can be applied to objects – it returns true if the
two references are aliases of each other
The equals method is defined for all objects, but unless we
redefine it when we write a class, it has the same semantics as
the
== operator
It has been redefined in the String class to compare
the characters in the two strings
When you write a class, you can redefine the equals
method to return true under whatever conditions are
appropriate
61. Exercis
e
Complete the Card Class
Add methods equals, compareTo, and toString
Add methods isFaceCard and isRed
Found in
http://www.cs.loyola.edu/~lawrie/CS630/F05/examples/Ex6/