Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

60 HOUR 5:Storing and Changing Information in a Program


The good news is that the computer does any math you ask it to do.
Expressions are used frequently in your computer programs to accomplish
tasks such as the following:

. Changing the value of a variable
. Counting the number of times something has happened in a program
. Using a mathematical formula in a program


As you write computer programs, you find yourself drawing on your old
math lessons as you use expressions. Expressions can use addition, sub-
traction, multiplication, division, and modulus division.
To see expressions in action, return to NetBeans and create a new Java file
with the class name PlanetWeight. This program tracks a person’s weight
loss and gain as she travels to other bodies in the solar system. Enterthe
full text of Listing 5.2 in the source editor. Each part of the program is dis-
cussed in turn.

LISTING 5.2 ThePlanetWeightProgram
1: classPlanetWeight {
2: public static voidmain(String[] args) {
3: System.out.print(“Your weight on Earth is “);
4: doubleweight = 205;
5: System.out.println(weight);
6:
7: System.out.print(“Your weight on Mercury is “);
8: doublemercury = weight * .378;
9: System.out.println(mercury);
10:
11: System.out.print(“Your weight on the Moon is “);
12: doublemoon = weight * .166;
13: System.out.println(moon);
14:
15: System.out.print(“Your weight on Jupiter is “);
16: doublejupiter = weight * 2.364;
17: System.out.println(jupiter);
18: }
19: }

When you’re done, save the file and it should compile automatically. Run
the program with the menu command Run, Run File. The output is shown
in the output pane in Figure 5.1.
Free download pdf