Java Reference
In-Depth Information
System. out . println(firstNumber) ;
System . out . println (secondNumber) ;
}
public static int readInteger () {
Scanner keyboard = new Scanner(System. in) ;
return keyboard . nextInt () ;
}
}
As a general rule, declare every variable in the innermost scope that you can live with.
Variables with a large scope make the program prone to errors. The second program is also
preferred because the readInteger method performs a single task. It is very likely that
a method that reads a single integer from the keyboard will be reused. However, we will
rarely need a method that reads two integers. This follows the rule that methods should be
simple and perform a single task.
4.6 The Trading Game
We will conclude this chapter with the first non-trivial game. We will create a Trading
Game . The game consists of 10 days. Every day, the player will be given the opportunity
to buy or sell apples and pears. The price of apples and pears will be determined using a
random number. The buying and selling will occur through a menu. We will add checks
to make sure the player cannot sell product they do not have or buy product they cannot
afford. The objective of the game is to make as much money as possible.
The game has some constants. For example, the number of days the game takes should
be a constant. Similarly, the numbers that are used in determining the price of apples and
pears should be constant. In general, your program should not have numerical numbers, such
as 10, inside the code. These are called magic numbers and are considered bad programming
practice. The reason is that one needs to search for them inside the code in order to change
them. Alternatively, these numbers can be defined as constants at the beginning of the
program. This is a better solution. You can think of constants as parameters to your program
that you can easily change.
Constants in Java are defined using the final keyword. For example, the following code
will define the number of days.
class TradingGame {
static final int NUMBER OF DAYS = 1 0 ;
...
}
The convention is that constants in Java are defined using all capital letters. Constants
are usually initialized at the time of declaration. The reason is that the value of a constant
cannot be modified.
We will use a top-down approach to design the program. We will start with the main
method. Inside it, however, we will call other methods that we will implement later. Here
is one possible implementation of the main method.
import java . text .
;
import java . util . ;
public class TradingGame
{
Search WWH ::




Custom Search