Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439

Computer Science Courses

Related sites

Introductory Programming In Java

Lab 3

Lab 3

Writing the code structurally

Objectives

Write and use methods to accomplish tasks.

Exercise One (warm up)

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,

Exercise Two (challenge)

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:

  1. There were no leap years before 1582.
  2. The year is not a leap year unless:
  3. It is divisible by 4, then it is a leap year unless:
  4. It is divisible by 100 in which case it is not, unless:
  5. It is divisible by 400.

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!

Optional extension to Exercise One

, 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 ints 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