Computer Science Courses
Related sites
Lab 3 |
Write and use methods to accomplish tasks.
Write a program which will print out the integers from 1 to 20 along with their halves. Calculate their halves in a separate method. (Remember that your method will have to be declared as being static
if it gets called from the main method and it is in the same class as the main
method.)
This exercise has an extension for those who is interested,
Our modern system of determining dates is known as the Gregorian Calendar. Since 1582, this calendar has had leap years. You can determine if a year is a leap year according to the following rules:
Write a method:
static boolean isLeapYear(int year)which returns
true
if the year is a leap year, and false
otherwise.Find someone else who has completed this exercise and test your method against theirs!
, from , is an example of a class which "wraps up" Java primitive data. In particular the BigInteger.valueOf()
method is a so-called factory method which wraps up a long datum and returns a new object of type BigInteger. (You can see how this method works by looking at various source code listings for BigInteger which you can find on the web eg:). Another example of a wrapper class is the WrapMyDouble class from .
For this optional extension problem, revise your answer to Exercise One by placing int
s into a wrapper class and pass an object of that wrapper class down to a function which halves the value of the wrapped int. Use "call by reference" as in the following code excerpt. For fun, you could even write your own factory valueOf()
method as was done forBigInteger.
One way of completing this exercise would be to fill out the dots in the following code excerpt:
public class LabThreeHalveInts { public static void main(String[] args) { WrapMyInt iWrapper; for (int k = 1; k <= 20; k++ ) { iWrapper = WrapMyInt.valueOf(k); halfValue(iWrapper); System.out.println(" k = " + k + " k/2 = " + iWrapper); } } public static void halfValue(WrapMyInt i) { // provide the method body } }public class WrapMyInt { // implement this class}
Lab 3 |
Updated: Sun 12 Jun 2016 17:27:37 AEST • Responsible Officer: JavaScript must be enabled to display this email address. • Page Contact:
+61 2 6125 5111
The Australian National University, Canberra
CRICOS Provider : 00120C ABN : 52 234 063 906