Selections (If-Else and Booleans) : COMP101: Introduction To Programming in JAVA
Selections (If-Else and Booleans) : COMP101: Introduction To Programming in JAVA
Lecture 16
Selections(If-else and Booleans)
Overview
Type Booleans
Range values false and true.
Keyword boolean
Boolean Expressions
A B !A A && B A || B
true true false true true
true false false false true
false true true false true
false false true false false
Problem
Write a program which allows the input of a 4-digit year, checks
that the input is in the correct range, checks whether it is a leap
year, and outputs this information.
Analysis
Write a program which allows the input an
4-digit year , checks that the input is in the
correct range , checks whether it is a leap year , and
outputs this.
Class Diagram
LeapYear
LeapYearUser
✲
- year: integer
+isLeapYear(): boolean
+ main(String[])
+getYear(): integer
Algorithm Design
The main method has the usual task of setting up all relevant
variables, then calling the isLeapYear method and finally
displaying the result of the computation. Note we can check the
input data is not negative using an if-else statement.
METHOD main
INPUT args
OUTPUT
LOCAL DATA someYear, MIN_YEAR = 0, MAX_YEAR=9999
READ someYear from the keyboard
IF someYear >= MIN_YEAR AND someYear <= MAX_YEAR
SET up an instance myLeapYear of LeapYear using someYear
as the year of the structure
PRINT a message with the result of
calculating the whether someYear is a Leap Year. ELSE
PRINT a message saying invalid year
Operations
How can we check if a year is a leap year?
Implementation:LeapYear
/**
* LeapYear.java, Based on code by Michele Zito
* Edited by Clare Dixon June 2010
**/
public class LeapYear {
// attributes
private int year;
// constructors
public LeapYear(int y) {
year = y;
}
// methods
public boolean isLeapYear() {
if (((year% 4 == 0) && (year % 100 != 0)) || ((year %
100 == 0) && (year % 400 == 0))) return true;
else
return false;
}
public int getYear() {
return year;
}
Implementation:LeapYearUser
/** LeapYearUser.java
* July 2010 Clare Dixon **/
import java.util.Scanner;
Output
$ java LeapYearUser
What’s the year? -10
Not a valid year.
$ java LeapYearUser
What’s the year? -1
Not a valid year.
$ java LeapYearUser
What’s the year? 0
The year 0 is a leap year.
$ java LeapYearUser
What’s the year? 10
The year 10 is not a leap year.
$ java LeapYearUser
What’s the year? 9999
The year 9999 is not a leap year.
Output
$ java LeapYearUser
What’s the year? 10000
Not a valid year.
$ java LeapYearUser
What’s the year? 1600
The year 1600 is a leap year.
$ java LeapYearUser
What’s the year? 1700
The year 1700 is not a leap year.
$ java LeapYearUser
What’s the year? 1704
The year 1704 is a leap year.
$ java LeapYearUser
What’s the year? 1705
The year 1705 is not a leap year.
(int) (int)
a b tmp tmp = b;
13 10 10
b is evaluated and its value assigned to tmp
(int) (int) (int)
b = a;
a 13 b 13 tmp 10
a is evaluated and its value assigned to b
(int) (int) (int)
a = tmp;
a 10 b 13 tmp 10
tmp is evaluated and its value assigned to a
(int) (int) (int)
Summary
Lecture 17
Selections: Switch
Overview
Switch
If a selection is based on the values of some expression, that
can be compared (easily/correctly) then a switch statement
may be used instead of a nested if-else.
Switch Example
Problem
We want to write a program that validates a date. The format of
the date DDMMYYYY is a single integer representing day,
month, and year. The single integer is split into individual
integers representing DD, MM, and YYYY. The program checks
that the number of months in a year should not exceed 12, and
that the number of days in each month has not been exceeded. The
program also reports on leap years.
Class Analysis
Class Analysis
Class Diagram
Date
- day: int
DateUser - month: int
✲ - year: int
+ main(String[]) -validateDate():
+isValid(): boolean
+isLeapYear(): boolean
Algorithm Design
What tasks need to be done?
Splitting the DDMMYYYY into parts relating to the day,
month, year.
Checking whether the year is a leap year.
Checking the month value is between 1 and 12.
Checking that the number of days is not greater than that
allowed for that month.
It is often useful to think of test cases at the design stage.
Are the following are valid dates? Why?
-03112011 0 13132012
03112011 32112011 28022011
29022011 28022012 29022012
Implementation of Date
/**
* Date - validates dates of the form DDMMYYYY
* Michele Zito
* Edited by Clare Dixon September 2010
**/
public class Date {
// attributes private int
day; private int month;
private int year;
// constructor
public Date(int rawDate) {
// split rowDate into month, day, and year
day = rawDate / 1000000;
month = (rawDate % 1000000) / 10000;
year = rawDate % 10000;
validateDate();
}
.........
Date validation
METHOD validateDate
INPUT
OUTPUT
LOCAL numberOfDays OF
DATA 7, 8, 10, or 12:
CASE month
1, numberOfDays
3, 5, is 31
4, 6, 9, or 11:
numberOfDays is 30
2:
IF it is a leap year
numberOfDays is 29
ELSE
numberOfDays is 28
OTHERS:
set day, month, year to error values
check day against numberOfDays
Implementation of Date
default :
day = 0;
month = 0;
year = -1;
break;
}
Constructors
We can check the validity of our data (not just date!) For
instance with a simple if statement we can discard values
outside a certain range.
DateUser
/*
* DateUser by Michele Zito
* Edited by Clare Dixon Sep 2010
*/
import java.util.Scanner;
Testing
Testing
Output
$ java DateUser
Input a date in the format DDMMYYYY -
Invalid date! 10121970
$ java DateUser
Input a date in the format DDMMYYYY
Invalid date! 0
$ java DateUser
Input a date in the format DDMMYYYY 10121970
It is a valid date and the year isn’t a leap year
$ java DateUser
Input a date in the format DDMMYYYY
Invalid date! 32012011
$ java DateUser
Input a date in the format DDMMYYYY 31012011
It is a valid date and the year isn’t a leap year
$ java DateUser
Input a date in the format
DDMMYYYY
Invalid date! 29022011
$ java DateUser
Input a date in the format
DDMMYYYY 28022011
It is a valid date and the
year isn’t a leap year
$ java DateUser
Input a date in the format DDMMY
Clare Dixon YYY 29022012
Selections: Switch 51 / 84
Lecture 16 Lecture 17 Lecture 18
Summary
Lecture 18
Aggregation
Overview
“Has–a” Relationships
System
PrintStream + out: PrintStream InputStream
✛ + in: InputStream ✲
....
Example
The class Student has attributes which are objects of Name and
Address.
Student Address
Name
- name: Name - city: String
- firstName: String
✛ - address: Address ✲ - postcode: String
- lastName: String
- studentID: String - country: String
// attributes
private String firstName;
private String lastName;
// constructors
public Name(String first, String last) {
firstName = first;
lastName = last;
}
.....
// attributes
private String city; private String
postcode; private String country;
// constructors
public Address(String theCity, String thePostcode, String theCountry) {
city = theCity;
postcode = thePostcode;
country = theCountry;
}
....
// constructors
public Student(String first, String last, String theCity, String thePostcode, String
theCountry,String studID) {
name = new Name(first, last);
address = new Address(theCity, thePostcode, theCountry);
studentID = studID;
}
......
}
Note that the constructor for Student calls the constructors for
Name and Address to instantiate the name andaddress attributes.
Problem
Produce a program that calculates the surface area and volume of a
cylinder given its radius and height. Assume that the radius and
height are input by the user as double precision floating point
numbers.
Cylinder
CylinderUser - radius: double
✲ - height: double
+ main(String[]) +volume(): double
+surfaceArea(): double
Cylinder
radius
height
Volume of a cylinder
= AreaOfEnd x height
Clare Dixon Aggregation 67 / 84
Lecture 16 Lecture 17 Lecture 18
Circle
- radius: double
+circumference(): double
+area(): double
✻
Cylinder
CylinderUser - cylinderEnd: Circle
✲ - height: double
+ main(String[]) +volume(): double
+surfaceArea(): double
Note that the interface to Cylinder doesn’t change so
application programs don’t need to know which version has
been implemented.
Clare Dixon Aggregation 68 / 84
Lecture 16 Lecture 17 Lecture 18
Algorithm Design
The main method has the usual task of setting up all relevant
variables, then calling the surfaceArea and volume methods
and finally displaying the result of the computation.
METHOD main
INPUT args
OUTPUT
LOCAL DATA myRadius, myHeight
READ myRadius and myHeight from the keyboard
IF both are non-negative values
SET up an instance myCylinder of Cylinder using
myHeight and an instance of Circle using myRadius
PRINT a message including the result of
calculating the surfaceArea and volume of myCylinder
ELSE
PRINT a message saying the input was negative
As the calculations for surfaceArea and volume are one line we
omit pseudocode for these.
Clare Dixon Aggregation 69 / 84
Lecture 16 Lecture 17 Lecture 18
Implementation: Cylinder
/**
* Cylinder.java - calculates the volume and surface area of a cylinder
* September 2010
* Clare Dixon
**/
public class Cylinder {
// attributes
private Circle cylinderEnd;
private double height;
// constructors
public Cylinder(double r, double h) { cylinderEnd
= new Circle(r); height = h;
}
Implementation: Cylinder
// methods
public double volume() {
//volume of a cylinder is a * height where
//a is the area of the circle
return cylinderEnd.area() height; *
}
Implementation: CylinderUser
/**
* CylinderUser.java - gets input data radius and height and
* creates a Cylinder to calculate surface area and volume
* September 2010
* Clare Dixon
**/
import java.util.Scanner;
Implementation: CylinderUser
Remarks
Testing
Testing
Testing Output
$ java CylinderUser
What’s the radius of the end of the cylinder? 0.0
What’s the height of the cylinder? 0.0
Surface Area = 0.0
Volume = 0.0
$ java CylinderUser
What’s the radius of the end of the cylinder? 0.0
What’s the height of the cylinder? 10.0
Surface Area = 0.0
Volume = 0.0
$ java CylinderUser
What’s the radius of the end of the cylinder? 0.0
What’s the height of the cylinder? -10.0
Negative value input: exiting.
$ java CylinderUser
What’s the radius of the end of the cylinder? 2.5
What’s the height of the cylinder? 0.0
Surface Area = 39.269908169872416
Volume = 0.0
Clare Dixon Aggregation 78 / 84
Lecture 16 Lecture 17 Lecture 18
Testing Output(Cont)
$ java CylinderUser
What’s the radius of the end of the cylinder? 2.5
What’s the height of the cylinder? 10.0
Surface Area = 196.34954084936209
Volume = 196.34954084936209
$ java CylinderUser
What’s the radius of the end of the cylinder? 2.5
What’s the height of the cylinder? -10.0
Negative value input: exiting.
etc
SwimmingPool
- RATEOFFLOW: double = 50.0
SwimmingPoolUser - UNITCAPACITY: double = 1000.0
✲ - length: double
+ main(String[]) - width: double
- depth: double
+timeToFill(): double
The Java keyword this is a reference to the object that uses it.
Summary