When you were in school, as you worked on a particularly unpleasant math problem, did you ever complain to a higher power, protesting that you would never use this knowledge in your life? Sorry to break this to you, but your teachers were right—your math skills come in handy in your computer programming. That’s the bad news.
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, subtraction, 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. Enter the full text of Listing 5.2 in the source editor. Each part of the program is discussed in turn.
1: class PlanetWeight {
2: public static void main(String[] args) {
3: System.out.print("Your weight on Earth is ");
4: double weight = 205;
5: System.out.println(weight);
6:
7: System.out.print("Your weight on Mercury is ");
8: double mercury = weight * .378;
9: System.out.println(mercury);
10:
11: System.out.print("Your weight on the Moon is ");
12: double moon = weight * .166;
13: System.out.println(moon);
14:
15: System.out.print("Your weight on Jupiter is ");
16: double jupiter = 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.
As in other programs you have created, the PlanetWeight
program uses a main()
block statement for all its work. This statement can be broken into the following four sections:
1. Lines 3–5: The person’s weight is set initially to 205.
2. Lines 7–9: Mercury weight loss is calculated.
3. Lines 11–13: Weight loss on the Moon is determined.
4. Lines 15–17: Jupiter weight gain is calculated.
Line 4 creates the weight
variable and designates it as an integer variable with int
. The variable is given the initial value 205 and used throughout the program to monitor the person’s weight.
The next line is similar to several other statements in the program:
System.out.println(weight);
The System.out.println()
command displays a string that is contained within its parenthesis marks. On Line 3, the System.out.print()
command displays the text “Your weight on Earth is”. There are several System.out.print()
and System.out.println()
statements in the program.
The difference between them is that print()
does not start a new line after displaying the text, whereas println()
does.
Now that you have been introduced to variables and expressions, you can give a wide range of instructions to your computer in a program. With the skills you have developed during this hour, you can write programs that accomplish many of the same tasks as a calculator, handling sophisticated mathematical equations with ease. You’ve also learned that a trip to the Moon is a particularly effective diet plan.
Numbers are only one kind of thing that can be stored in a variable. You also can store characters, strings of characters, and special true
or false
values called boolean
variables. The next hour expands your knowledge of String
variables and how they are used.
Q. Is a line in a Java program the same thing as a statement?
A. No. The programs you create in this book put one statement on each line to make the programs easier to understand; it’s not required.
The Java compiler does not consider lines, spacing, or other formatting issues when compiling a program. The compiler just wants to see semicolons at the end of each statement. This line would work just fine in Java:
int x = 12; x = x + 1;
Putting more than one statement on a line makes a program more difficult for humans to understand when they read its source code. For this reason, it is not recommended.
Q. Why should the first letter of a variable name be lowercase, as in gameOver
?
A. It’s a naming convention that helps your programming in two ways. First, it makes variables easier to spot among the other elements of a Java program. Second, by following a consistent style in the naming of variables, you eliminate errors that can occur when you use a variable in several different places in a program. The style of capitalization used in this book is the one that’s been adopted by most Java programmers over the years.
Q. Can I specify integers as binary values in Java?
A. You can for the first time in Java 7. Put the characters 0b
in front of the number and follow it with the bits in the value. Because 1101 is the binary form for the number 13, the following statement sets an integer to 13:
int z = 0b0000_1101;
The underscore is just to make the number more readable. It’s ignored by the Java compiler.
NetBeans will treat this feature as an error unless your project has been set up to use Java 7. You learn how to do this in Hour 7.
Q. What the heck are Larvets?
A. Larvets, the product mentioned in this hour, are snacks made from edible worms that have been killed, dried, and mixed with the same kinds of scrumptious food-like flavoring as Doritos chips. You can order Larvets in three flavors—BBQ, cheddar cheese, and Mexican spice—from the mail-order retailer HotLix at the website www.hotlix.com or by calling 1-800-EAT-WORM.
Test your knowledge of variables, expressions, and the rest of the information in this hour by answering the following questions.
1. What do you call a group of statements that is contained with an opening bracket and a closing bracket?
A. A block statement
B. Groupware
C. Bracketed statements
2. A boolean
variable is used to store true
or false
values.
A. True
B. False
C. No, thanks. I already ate.
3. What characters cannot be used to start a variable name?
A. A dollar sign
B. Two forward slash marks (//
)
C. A letter
1. A. The grouped statements are called a block statement or a block.
2. A. true
and false
are the only answers a boolean
variable can store.
3. B. Variables can start with a letter, a dollar sign ($
), or an underscore character (_
). If you started a variable name with two slash marks, the rest of the line would be ignored because the slash marks are used to start a comment line.
You can review the topics of this hour more fully with the following activities:
• Expand the PlanetWeight
program to track a person’s weight on Venus (90.7% of Earth weight) and his weight on Uranus (88.9% Earth)—and stop snickering because I mentioned Uranus.
• Create a short Java program that uses an x
integer and a y
integer and displays the result of x
squared plus y
squared.
To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.
3.133.136.73