Lecture Notes, class 5 for csc211.
Prepared by: Anthony Larrain
These notes serve as an outline to the lecture, they are not intended to be complete. You should be reading the assigned sections. During class I may include or omit certain topics.
The while Statement
Recall three ways to alter flow of control
- invoking a method
- decisions( if - else )
- looping
while( condition )
{
// Execute this block while the condition is true.
}
- Used to execute a statement or statements multiple times.
- Uses a boolean expression as the condition.
- If the condition is true and the statement is executed control jumps back to the condition.
- The curly braces are needed if the loop block has more than one statement.
Examples using while loop.
// Prints the numbers 1 to and including 10
int i = 1;
while( i <= 10 )
{
System.out.println( i );
i += 1; // Same as i = i + 1;
}
// Count down from 100, stop at 1
int i = 100;
while( i > 0 )
{
System.out.println( i );
i -= 1; // Same as i = i - 1;
}
// Print the numbers 1 to 100 except 50;
int i = 1;
while( i <= 100 )
{
if ( i == 50 )
++i;
System.out.println(i);
++i;
}
- In a count-controlled loop, the loop body is executed a fixed number of times.
- In a sentinel-controlled loop, the loop body is executed repeatedly until a designated value, called a sentinel, is encountered
See DiceGame2.java
More on if - else
- If any of the blocks contain only one statement then the braces are optional.
- Good for beginners to always put in the braces.
- Can get confusing.
- An if-else is used when data falls into two mutually exclusive categories.
- Pass or Fail
- Roll a seven or Not.
- Heads or Tails
- Valid data or invalid data
- Can combine if-else together with flexibility in using spaces and braces to handle data that is more than two mutually exclusive categories.
- To deal with data that falls into more than two mutually exclusive categories, we construct an if - else - if ladder.
- Noticed the braces are removed for the ones that have only one statement
if( condition )
{
execute this block only if the condition is true.
}
else
{
execute this block if the condition is false.
}
int score = 78;
if(score > 59)
System.out.println("You passed");
else
System.out.println("You failed");
System.out.println("See ya);
// output is .. You passed and See ya
int score = 78;
if(score > 59)
System.out.println("You passed");
else
System.out.println("You failed");
System.out.println("See ya);
// output STILL is .. You passed and See ya
if(condition 1)
{
execute this block if condition 1 is true
}
else if(condition 2)
{
execute this block if condition 2 is true
}
else if(condition 3)
{
execute this block if condition 3 is true
}
else
{
execute this block if all the above conditions are false.
}
Example 1
int score = 85;
if(score >= 90)
{
System.out.println("Excellent");
}
else if (score >= 60) {
System.out.println("You passed");
}
else {
System.out.println("You failed");
}
System.out.println("See ya");
// Output is .. You passed and See ya
Example 2
int score = 95;
if(score >= 90)
{
System.out.println("Excellent");
}
else if (score >= 60) {
System.out.println("You passed");
}
else {
System.out.println("You failed");
}
System.out.println("See ya");
// Output is .. Excellent and See ya
Example 3
int score = 55;
if(score >= 90)
{
System.out.println("Excellent");
}
else if (score >= 60) {
System.out.println("You passed");
}
else {
System.out.println("You failed");
}
System.out.println("See ya");
// Output is .. You failed and See ya
Example 4
int score = 85;
if(score >= 90)
{
System.out.println("Excellent");
}
else if (score >= 75) {
System.out.println("Good");
}
else if (score >= 60) {
System.out.println("You passed");
}
else {
System.out.println("You failed");
System.out.println("Retake");
}
System.out.println("See ya");
// Output is .. Good and See ya
Example 4
int score = 85;
if(score >= 90)
System.out.println("Excellent");
else if (score >= 75)
System.out.println("Good");
else if (score >= 60)
System.out.println("You passed");
else {
System.out.println("You failed");
System.out.println("Retake");
}
System.out.println("See ya");
// Output is .. Good and See ya
Logical Operators
Simple boolean expressions can be joined together using the relational operators. A simple boolean expression consists of two operands and one relational or equality operator.
! -- NOT && -- AND || -- OR
NOT has the highest precedence of the Logical operators, followed by AND then by OR. The logical operators have lower precedence than the relationaloperators.
if( age > 12 && age < 20)
Your a teen
if( result == 7 || result == 11 )
you won
boolean value = false;
if( !value )
value is false
if( score >= 0 && score <= 100)
valid score
Increment and Decrement Operators
- Unary operators that operate on variables of integer and floating point types.
- Easy way to add or subtract the number one from a variable.
The Increment operator   ++
int days = 20; ++days; // changes days to 21 int weeks = 23; ++weeks; // changes weeks to 24 ++weeks; // changes weeks to 25
The Decrement operator   --
int hrs = 12; --hrs; // changes hrs to 11
More Operators
- The Assignment Operator ( = ) , gives a variable a value.
- +=
int sum = 30; sum += 5; now sum is 35 Equivalent to sum = sum + 5; - -=
int a = 5; a -= 2; a is 3 Equivalent to a = a - 2; - *=
int x = 20; x *= 3; x is now 60 Equivalent to x = x * 3; - /=
int z = 40; z /= 2; z is now 20 Equivalent to z = z / 2;
Shorthand Assignment Operators
Characters
- In Java, single characters are represented using the data type
char. - Character constants are written as symbols enclosed in single quotes:
char ch1 = ‘X’; String street = "western"; char firstChar = street.charAt(0);
Question
What is the difference between ..
'F' AND "F"
Example 1
This program will assign a letter grade to an average
import java.util.Scanner;
class Grade {
public static void main(String [] args){
Scanner readScore = new Scanner(System.in):
System.out.println("Enter you final average");
int avg = readScore.nextInt();
char grade;
if(avg >= 90){
grade = 'A';
}
else if(avg >= 80){
grade = 'B';
}
else if(avg >= 70){
grade = 'C';
}
else if(avg >= 60){
grade = 'D';
}
else{
grade = 'F';
}
System.out.println("Your grade is " + grade);
}
}
Example 2
Same as example 1, except braces are removed.
import java.util.Scanner;
class Grade {
public static void main(String [] args){
Scanner readScore = new Scanner(System.in):
System.out.println("Enter you final average");
int avg = readScore.nextInt();
char grade;
if(avg >= 90)
grade = 'A';
else if(avg >= 80)
grade = 'B';
else if(avg >= 70)
grade = 'C';
else if(avg >= 60)
grade = 'D';
else
grade = 'F';
System.out.println("Your grade is " + grade);
}
}
Increment and Decrement Operators
- Unary operators that operate on variables of integer and floating point types.
- Easy way to add or subtract the number one from a variable.
The Increment operator   ++
int days = 20; ++days; // changes days to 21 int weeks = 23; ++weeks; // changes weeks to 24 ++weeks; // changes weeks to 25
The Decrement operator   --
int hrs = 12; --hrs; // changes hrs to 11