Next: Tutorial 7 Non-Object arrays, Previous: Tutorial 5 A beer drinking song, Up: J.T.W. Tutorials [Contents][Index]
Question 4.6.1: Study, compile and run the following code. Note the use
of the class variable myMoney. A class variable is different from a
variable that is local to a function because the lifetime of the class
variable is for the duration that the program is run, whereas the
lifetime of a local variable is for the duration of the function
call. In the code that follows, the variable myMoney is used to
store a numerical value, for how much money you have.
classMoneybegin/** Property myMoney stores money value in dollars */classVarint myMoney;functionvoid spend(String item, int value)beginmyMoney = myMoney - value; System.out.println("*** spent $" + value + " on " + item + ", leaving you with $" + myMoney);endendbeginMainmyMoney = 100; spend("aquarium",50); spend("shoes",100); spend("lipstick",20);endMainend
Question 4.6.2: Change the myMoney class variable so that it is a double
(short for double-precision floating point) rather than an int. You
will need to add a new function money2string that converts double
values into strings. For example the floating point number 1.2345
should be printed out as $1.23. If x is a double then the following
expression converts x from a double into a number of dollars (int)x
and the following expression converts x into a number of cents
(int)(money * 100) - 100 * dollars. Note that you will need to make it
so that $1.03 prints out as this value.
Question 4.6.3: Add an if statement to the spend function so that it
uses System.out.println() to print out an error message if the
person does not have enough funds in their bank account to pay for the
item parameter.
Question 4.6.4: Add a new class variable double
governmentsMoney and make it so that 12.5% of the cost of each
item goes to the government in the form of G.S.T., which stands for
Goods and Services Tax, a value-added tax.
Question 4.6.5: Add a new class variable numBattleships that records
how many batteships are owned by the government. Write a function
buyBattleShips that causes the government to buy as many battleships
as it can afford. Make it so that the buyBattleShips function prints
out how many battleships were purchased. Let the cost of each
battleship be one million dollars and store this value in a variable
called costOfShip. Please note that if the government’s money is less
the one million dollars then no battleships will be purchased.
Question 4.6.6: Set the initial value for governmentsMoney to be two
millions dollars, then call the buyBattleShips function and verify
that two battleships were purchased.
Next: Tutorial 7 Non-Object arrays, Previous: Tutorial 5 A beer drinking song, Up: J.T.W. Tutorials [Contents][Index]