Exercises
1. An application is required to calculate the volume of a fish tank, given its
length, width and depth in millimetres. The volume should be given to the
nearest litre.
a)
Analyse this problem. What are the inputs and outputs? What types
of data are needed? What calculations are needed?
b)
Having determined the variables you will need, and their types
(long and/or double), use Eclipse to write your program in a
new class called Tank. Use the JOptionPane class for I/O.
Notes:
? The volume of a large tank, say 3000mm long by 1000mm wide by
1000mm deep may be too big to store as an int. Use long rather
than int to avoid "loss of precision" errors.
2. The following application (included as one of the examples) demonstrates the
use of Java library classes Calendar and GregorianCalendar¹ for date
manipulation.
import static javax.swing.JOptionPane.*;
import java.util.*;
class DateDemo {
public static void main(String[] args) {
GregorianCalendar now = new GregorianCalendar();
int thisYear = now.get(Calendar.YEAR);
showMessageDialog(null, "This year is " + thisYear);
}
}
Here a GregorianCalendar object now is created with
and time and the statement
int thisYear = now.get(Calendar.YEAR);
Make use of these classes in a similar fashion to modify HelloAge.java
(Lecture notes 1) so that it asks for the user's age at the end of this year and
displays the user's year of birth. Save your modified program as
FindMyBirthYear.java.
Input
Input
Please type your name
James
How old will you be at the end of this year
25
OK
Cancel
OK
Cancel
Message
Hello James. You were born in 1983
OK
Message
This year is 2009
OK
Calendar objects have several fields
that you can get and set, including
this one, Calendar.MONTH,
Calendar.DAY_OF_WEEK and so on