Post date: Apr 09, 2018 11:0:53 AM
Defining Classes 1
4.4 Constructors
Recommended Self-Test Exercises:
p 268-269: Ex. 24-26.
Exercise 1: Class Temperature
Write a Temperature class that has two instance variables: a temperature value (a floating-point number) and a character for the scale, either 'C' for Celsius or 'F' for Fahrenheit.
The class should have four constructor methods:
one for each instance variable (assume zero degrees if no value is specified and Celsius if no scale is specified),
one with two parameters for the two instance variables, and
a no-argument constructor (set to zero degrees Celsius).
Include two accessor methods ("getters") to return the temperature:
getTempCelsius: to return the degrees Celsius,
getTempFahrenheit: to return the degrees Fahrenheit
IMPORTANT: use the following formulas :
degreesC = 5(degreesF - 32)/9
degreesF = (9(degreesC)/5) + 32
Include three mutator methods ("setters"):
setValue to set the value,
setScale to set the scale ('F' or 'C'), and
setValueAndScale to set both;
Include a suitable toString method.
Include a equals method
Then write a test class called TestTemperature that tests all the methods. Make sure to use each of the constructors.
Exercice 2: Class Time
public class Time {
/* Three instance variables:
1) 'hour': value of a hours as integer
2) 'min': value of a minutes as integer
3) 'sec' : value of a seconds as integer */
/* A three-argument constructor to initialize all instance variables with values given as parameters if they are valid values using 24 hours format */
/* A mutator (setter) method that sets the 'sec' field to a value given as a parameter, but only if the given value is valid */
/* A toString method that returns time as 12 hours format */
/* An method that increments time by a positive number of seconds given as a parameter only if value is less than or equal 59 */
}
5.1 Static methods and static variables
Recommended Self-Test Exercises:
p 299: Ex. 1-6.
p 309: Ex. 14-16.
Exercises:
Write a static method that takes as input an integer value and returns the sum of all integers less than that value. For example, if the input is 6, the output is 5+4+3+2+1 = 15. If the input is negative, the output should be -1.
Write a static method that takes as input an array of integers and returns the average of the values in the array.
Write a static method public void printTriangleNumbers(int n) such that:
The call: printTriangleNumbers(5) prints the following on the screen:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
The call: printTriangleNumbers(6) prints the following on the screen:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
The call: printTriangleNumbers(3) prints the following on the screen:
1 2 3
1 2
1